【问题标题】:How do I add a button to the left side of the toolbar?如何在工具栏的左侧添加一个按钮?
【发布时间】:2022-01-05 07:05:00
【问题描述】:

我有两个片段。当我从第一个片段切换到第二个片段时,工具栏上会显示一个后退箭头。如何让主屏幕上没有空白而不是返回箭头,但是有另一个按钮?

工具栏:

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:minHeight="64dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

两个屏幕:

【问题讨论】:

标签: android kotlin android-fragments navigation toolbar


【解决方案1】:

我通过添加自己的按钮解决了这个问题。

<ImageButton
    android:id="@+id/button_settings"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?attr/actionBarItemBackground"
    app:srcCompat="@drawable/ic_settings" />

请注意,通过指定android:background="?attr/actionBarItemBackground",您可以获得与常规工具栏按钮相同的点击效果。

如果您想在某些屏幕上隐藏您的按钮,请将 addOnDestinationChangedListener 添加到 NavController

navController.addOnDestinationChangedListener { _, destination, _ ->
    binding.buttonSettings.visibility =
        if (destination.id == R.id.account_add_fragment) View.GONE else View.VISIBLE
}

【讨论】:

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