0

我在理解 Android 主详细信息模板中的向上导航时遇到问题。在单窗格模式下(对于智能手机),我使用 ItemListActivity 和 ItemListFragment。如果单击 ListFragment 中的项目,则会调用 ItemDetailFragment。现在,如果我在这个 ItemDetailFragment 中,我想通过单击 ActionBar 中的向上导航返回 ItemListFragment。

我是这样理解的:我只需要用 ItemListFragment 替换我的 ItemDetailFragment,还是?

在我的 ItemDetailFragment 中,我使用以下代码:

//OnClick auf ActionBar
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home: 
          FragmentTransaction trans = getFragmentManager().beginTransaction();
          trans.replace(R.id.fragment_container, new ItemListFragment()); 
          trans.commit();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

但是 ItemListFragment 并不处于调用 DetailFragment 之前的状态。我想要和以前一样的列表。

如果我单击后退按钮,则正确的操作已完成,那么我是否应该在向上导航中实现后退单击?

4

2 回答 2

2

使用您当前的方法,您可以创建 ItemListFragment 的新实例,因此如果您想保存列表的状态,您需要自己完成。你需要简单地回去然后我建议调用onBackPressed()主页按钮的方法。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home: 
          this.onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
于 2013-11-12T16:07:46.540 回答
1

据我了解你上面的描述..

1)如果您在 Listfragment 项目中单击 .. ,那么您将移至 ItemdetailFragment ,因此您需要在 ListFragment 中添加 BackStack 操作。即如下

transaction.addToBackStack(String);//to identify you can give any name 
transaction.commit();  //then commit the transaction

2)当您想从 ItemdetailFragment 移动到 ListFragment 时,您正在使用后退按钮,在这种情况下,您需要调用后退按钮

popBackStack("towhich screen you want to move",0) //for more information 参考这个

于 2013-11-13T09:45:20.547 回答