【问题标题】:ActionBar back button finishing activity from inner Fragment内部 Fragment 中的 ActionBar 后退按钮完成活动
【发布时间】:2017-07-25 14:14:13
【问题描述】:

我有一个 AppCompatActivity 和一个带有后退按钮的 ActionBar。我正在启动一个内部 Fragment 类,它在 Activity 视图顶部打开一个视图。硬件后退按钮关闭 Fragment,Activity 视图可见。但是,如果我在 Fragment 视图中按下 ActionBar 上的后退按钮,应用程序将返回到 MainActivity,即活动父级。我想隐藏 ActionBar,或者理想情况下给它与硬件按钮相同的行为,因为这对用户来说显然是烦人的行为。我尝试在我的 Activity 中创建 ActionBar 的实例,就像这样

ActionBar actionBar = getActionBar();
actionBar.setHomeAsUpEnabled(true);

这在运行时给了我一个NullPointerException。我已经搜索并被难住了。

也试过这个,mFragmentManager 在开始与我的 Fragment 类的事务之前有 .addToBackStack()。

@Override
public void onBackPressed() {

    int count = mFragmentManager.getBackStackEntryCount();

    if (count == 0) {
        super.onBackPressed();
        //additional code
    } else {
        mFragmentManager.popBackStack();
    }
    Log.i(LOG_TAG, "onBackPressed. Count = " + count);
}

~没有错误,但 ActionBar 后退按钮的行为没有改变。没有记录日志信息~

我的错误,这种方法确实改变了行为,但对于硬件后退按钮。当尝试在mFragmentManager 上使用getBackStackCount() 时,它会导致NullPointerException

【问题讨论】:

    标签: java android android-fragments android-actionbar


    【解决方案1】:

    操作栏的“后退”按钮实际上是 Up 按钮,根据 Google 的说法,它的行为应该与硬件后退按钮不同:https://developer.android.com/training/design-navigation/ancestral-temporal.html

    话虽如此,您可以拦截对该按钮的触摸,然后对它们做任何您想做的事情。

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            // your code here
        }
    
        return super.onOptionsItemSelected(item);
    }
    

    【讨论】:

    • 'android.R.id.home' 是 Android Manifest 中的顶级活动?还是我需要链接到我的 activity_main.xml?如何通过 xml 布局名称或活动名称重定向到我的活动?
    • android.R.id.home 是操作栏中主页按钮的 ID(通常会有一个箭头图标)。这适用于所有活动,无需更改清单。
    • 啊,我明白了。那么在 if 方法语句中,我可以使用 Intent 导航回我的 Activity 吗?这感觉很可惜,因为我预计数据会重新加载,但仍然比以前好。
    • 如果您只想将片段从后端堆栈中弹出,您可以在 if 语句中插入类似getSupportFragmentManager().popBackStack(); return true; 的内容。
    • 当然,这假设您在显示片段时实际上已将片段事务添加到后台堆栈。
    【解决方案2】:

    尝试改用getSupportActionBar()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      相关资源
      最近更新 更多