【发布时间】:2014-04-26 00:19:43
【问题描述】:
我目前正在为我要开发的应用程序布置基础知识。有一个带有几个分配给它的菜单项的操作栏。每个菜单项都有自己的片段,需要在主活动中显示。但是,我希望在显示除 MainFragment 本身之外的任何片段时显示操作栏的“向上”功能。
我目前的方法是基于actionbar up navigation with fragments 提出的解决方案,看起来像这样:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.action_identities) {
fragment = new IdentitiesFragment();
} else if (id == R.id.action_history) {
fragment = new HistoryFragment();
} else if (id == R.id.action_settings) {
fragment = new SettingsFragment();
} else if (id == R.id.action_about) {
fragment = new AboutFragment();
}
if (fragment != null) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackStackChanged()
{
displayHomeAsUp();
}
private void displayHomeAsUp()
{
int stackCount = getFragmentManager().getBackStackEntryCount();
getActionBar().setDisplayHomeAsUpEnabled(stackCount > 0);
}
@Override
public boolean onNavigateUp()
{
getFragmentManager().popBackStack();
return true;
}
这很好用,但是在多次按下同一个菜单项时会出现问题,因为每次都会将片段的新实例放入后堆栈。防止这种情况发生的最好方法是什么?显然我可以检查当前显示的片段是否是被请求的片段,但这会导致大量检查并且有点多余。另一种方法可能是事务标签,但我不确定这是否会产生更清晰的代码。
最好的方法是什么?这不是一个普遍的问题,还是我希望应用程序“表现”错误的方式?因为我个人非常喜欢操作栏的“向上”功能。
【问题讨论】:
标签: android android-fragments fragment back-stack