如何在 Material 设计中创建后退按钮

How to create a Back Button in Material Design

我找不到有关在 Material 设计中的操作栏中添加此按钮的教程。

如何将其添加到 Lollipop 的操作栏中?

试试这个

在创建中:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

在您的 activity class 中(假设您要关闭此 activity)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        finish();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

Material Design Tutorial 这将使您简要了解如何实施 material app.

如果您将 ActionBarActivityAppCompat Theme 一起使用,请使用:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

您可能还必须以同样的方式调用 setHomeButtonEnabled(true)。 它看起来像这样:


首先,你必须使用Material DesignTheme,而Theme支持ActionBar,例如 Theme.AppCompat.LightTheme.AppCompat.Light.DarkActionBar
第二个,调用ActionBar.setDisplayHomeAsUpEnabled(true);ToolBar.setDisplayHomeAsUpEnabled(true);,然后会显示Return图标。

在您的 onCreate 中添加这些行

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

对于后退导航,您必须在 AndroidMnifest.xml

上定义后退导航活动
<activity 
android:name=".CurrentActivity" 
android:label="@string/app_name"
android:parentActivityName=".BackActivity">
</activity>

getSupportActionBar().setDisplayHomeAsUpEnabled(true);可能会产生空指针异常,onCreate()应该是这样的。

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();
}

/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
private void setupActionBar() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        // Show the Up button in the action bar.
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}