【问题标题】:Is there a way to make AppCompat's ActionBar's "back/up" button act as the "back" system button有没有办法让 AppCompat 的 ActionBar 的“后退/向上”按钮充当“后退”系统按钮
【发布时间】:2014-12-02 08:18:07
【问题描述】:

我有一个包含几个活动的应用程序。到目前为止,我在它们之间有一个“硬编码”层次结构,所以我在它们的每个(但启动器活动)中明确设置了 android:parentActivityName。但是现在我将设置添加到多个活动的菜单中。

有没有办法让操作栏中的“后退”箭头作为系统的后退按钮(在屏幕底部)?换句话说:如果设置了 parentActivityName,则返回父活动,如果没有,则关闭活动并“返回”前一个活动。

这是我尝试过的,但不起作用。如果我不调用 actionBar.setDisplayHomeAsUpEnabled(true),那么操作栏中没有“后退”箭头,但如果我在 Manifest 中没有设置 parentActivityName 的活动中调用它,那么当我点击箭头。

abstract public class BaseActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResourceId());

        final ActionBar actionBar = getSupportActionBar();
        if (null != actionBar) {
            actionBar.setDisplayHomeAsUpEnabled(getDisplayHomeAsUpEnabled());
        }
    }

    protected abstract int getLayoutResourceId();
    abstract protected boolean getDisplayHomeAsUpEnabled();

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        final int id = item.getItemId();
        if (id == android.R.id.home) {
            NavUtils.navigateUpFromSameTask(this);
            return true;
        }
    }
}

【问题讨论】:

    标签: android back-button android-appcompat android-actionbar-compat android-homebutton


    【解决方案1】:

    试试:

        if (id == android.R.id.home) {
            onBackPressed();
            return true;
        }
    

    上面的代码会调用你的onBackPressed,所以如果你覆盖了它要小心。否则,它会像“返回”系统按钮一样。

    【讨论】:

    • 当清单中未设置 android:parentActivityName 时,这仍然无法帮助我显示箭头
    • @Gavriel 我不使用android:parentActivity,我只是在上面的代码中使用setDisplayHomeAsUpEnabled(true);,它的工作原理就像返回系统按钮
    • 好的,它确实有效。现在我可以在每个活动上调用 actionBar.setDisplayHomeAsUpEnabled(true)。
    • @Gavriel 很高兴为您提供帮助 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多