如何在Toolbar的后退箭头上显示和设置点击事件?

新手上路,请多包涵

工具栏上的后退按钮

如何在 Android 工具栏中设置后退箭头并应用点击监听器?

原文由 Abhijeet Mallick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 516
2 个回答

先做一个 toolbar.xml

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

然后将其包含在 activity_main.xml 中,如下所示:

 <LinearLayout
    android:id="@+id/container_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

</LinearLayout>

然后在您的 MainActivity.java 文件中,输入以下代码:

 mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("MyTitle");

要在后按时添加侦听器,请使用以下方法:

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // todo: goto back activity from here

            Intent intent = new Intent(CurrentActivity.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
            return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}

原文由 Pratik Tank 发布,翻译遵循 CC BY-SA 3.0 许可协议

Toolbar mToolbar= (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // perform whatever you want on back arrow click
    }
});

// 使用 lamda 表达式

toolbar.setNavigationOnClickListener(view -> onBackPressed());

原文由 sagar.android 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题