我的问题是理解如何正确使用意图。在谷歌搜索并阅读了有关该主题的所有文档和文章之后,我仍然无法解决我的问题。我有两个活动:“Searchable”和“ActivityWordInfo”。 “Searchable”活动在数据库中搜索一个词,并显示搜索结果或建议。用户点击其中一个搜索结果后,将启动“ActivityWordInfo”活动并显示单词定义。这是代码的一部分:
可搜索:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get the intent, verify the action and get the query
if( savedInstanceState != null ){
//the application is being reloaded
query = savedInstanceState.getString("searchedWord");
doMySearch(query); //does the search in the database
}else{
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
}
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("searchedWord", query);
//saves the searched word if this activity is killed
}
@Override
public void onClick(View v) { //when one of the search results is clicked
int wordID = (Integer) v.getTag();
Intent intent = new Intent(Searchable.this, ActivityWordInfo.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
Bundle b = new Bundle();
b.putInt("key", wordID);
b.putInt("calling_activity", callingActivityId);
intent.putExtras(b);
startActivity(intent);
}
ActivityWordInfo:
public void onCreate(Bundle savedInstanceState) {
...
Bundle b = getIntent().getExtras();
current_word_id = b.getInt("key", 0);
callingActivityId = b.getInt("calling_activity", 0);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
switch(callingActivityId){
case 3: //which is the ID of Searchable activity
Intent intent3 = new Intent(ActivityWordInfo.this, Searchable.class);
intent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent3);
break;
}
break;
}
当用户在 ActivityWordInfo 中并向上导航时,我希望转到 Searchable 活动,它应该已经保存了它的实例状态(结果列表应该仍然存在)。现实中发生了什么: - 将用户输入的词分配给'query'变量,然后在“Searchable”中显示结果和建议 - 用户单击其中一个单词并创建“ActivityWordInfo” - 然后,当用户向上导航时,将调用 onSaveInstanceState 以获取“Searchable”活动,然后销毁并创建它。结果是一个空布局 :(
我无法理解为什么“Searchable”被销毁然后又被创建!这只发生在 Android 4.2 中,而不是在较低的 API 中(在 2.3.3 中工作得很好,正如我预期的那样)。 JellyBean 中的 Activity 生命周期有什么不同吗?
注意:我不能在清单中使用 parentActivity 属性,因为 ActivityWordInfo 被多个父级调用。
“向上”导航的行为在 2.3 和 4.0 之间发生了变化。我建议你看看 developer.android.com 上的主题“Tasks and Back Stack”。