我正在应用程序中从ActionBar迁移到工具栏。 但我不知道如何显示和设置单击事件在工具栏上的后退箭头,就像我在动作栏上做的那样。

使用ActionBar,我调用mActionbar.setDisplayHomeAsUpEnabled(true)。 但是没有类似的方法。

有没有人遇到过这种情况,并以某种方式找到了解决它的方法?


当前回答

如果你想要得到工具栏上的后退箭头,而不是设置为你的SupportActionBar:

(kotlin)

val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator)
toolbarFilter.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId)
toolbarFilter.setNavigationOnClickListener { fragmentManager?.popBackStack() }

从属性中获取res:

@AnyRes
fun getResIdFromAttribute(context: Context, @AttrRes attr: Int): Int {
    if (attr == 0) return 0
    val typedValueAttr = TypedValue()
    context.theme.resolveAttribute(attr, typedValueAttr, true)
    return typedValueAttr.resourceId
}

其他回答

如果您正在使用JetPack导航。

这是MainActivity的布局

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                               xmlns:app="http://schemas.android.com/apk/res-auto"
                                               xmlns:tools="http://schemas.android.com/tools"
                                               android:layout_width="match_parent"
                                               android:layout_height="match_parent"
                                               tools:context=".MainActivity">

<androidx.appcompat.widget.Toolbar
        android:id="@+id/toolBar"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

</androidx.appcompat.widget.Toolbar>

<fragment
        android:id="@+id/my_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintTop_toBottomOf="@id/toolBar"
        app:layout_constraintBottom_toTopOf="parent"
        app:navGraph="@navigation/nav_graph"/>

在activity类的onCreate()中设置你的工具栏,如下所示。

val navHostFragment = supportFragmentManager
        .findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment? ?: return

val navController = navHostFragment.findNavController()
val toolBar = findViewById<Toolbar>(R.id.toolBar)
setSupportActionBar(toolBar) // To set toolBar as ActionBar
setupActionBarWithNavController(navController)

如果需要,将在工具栏上创建一个后退按钮,并处理后退按钮功能。 如果你需要写一个CustomBack功能,在你的onCreate()方法上创建一个callBack,如下所示

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
        // Handle the back button event
    }

从文档:https://developer.android.com/guide/navigation/navigation-custom-back

你很容易就能做到。

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

学分: https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e

简单和容易的方法显示工具栏上的返回按钮

将此代码粘贴到onCreate方法中

 if (getSupportActionBar() != null){

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

将这个覆盖方法粘贴到onCreate方法之外

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== android.R.id.home) {

        finish();
    }
    return super.onOptionsItemSelected(item);
}

如果你正在使用AppCompatActivity并且已经走下了不使用它的路径,因为你不想得到它提供的自动动作栏,因为你想要分离工具栏,因为你的材质设计需求和CoordinatorLayout或AppBarLayout,那么,考虑一下:

你仍然可以使用AppCompatActivity,你不需要为了使用<android.support.v7.widget而停止使用它。xml中的工具栏>。只需关闭操作栏样式,如下所示:

首先,在你的styles.xml中从一个你喜欢的NoActionBar主题中派生一个样式,我使用Theme.AppCompat.Light.NoActionBar像这样:

<style name="SuperCoolAppBarActivity" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/primary</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">@color/primary_dark</item>
    ...
    ...
</style>

在你的App的manifest中,选择你刚刚定义的子样式主题,如下所示:

    <activity
        android:name=".activity.YourSuperCoolActivity"
        android:label="@string/super_cool"
        android:theme="@style/SuperCoolAppBarActivity">
    </activity>

在你的Activity Xml中,如果工具栏是这样定义的:

...
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        />
...

然后,这是重要的部分,你将支持操作栏设置为你正在扩展的AppCompatActivity,这样xml中的工具栏就变成了操作栏。我觉得这是一种更好的方法,因为你可以简单地做ActionBar允许的许多事情,如菜单、自动活动标题、项目选择处理等,而不需要添加自定义点击处理程序等。

在你的活动的onCreate覆盖,做以下:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_super_cool);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);
    //Your toolbar is now an action bar and you can use it like you always do, for example:
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} 

而Kotlin则变成了:

Xml:

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

在活动中:-

setSupportActionBar(tbSignToolbar as Toolbar?)//tbSignToolbar :id of your toolbar 
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)