如何在 android 应用工具栏的左侧添加一个按钮?

How to add a button on the left side of android app toolbar?

我想在 android 应用程序工具栏的左侧添加一个 **add 按钮

您可以创建自定义工具箱并根据需要进行设计。

您可以将工具栏替换为您刚刚创建的自定义布局。

YourActivity.java中使用这个,

Toolbar toolbar = findViewById(R.id.Toolbar);
        toolbar.setTitle("ORDERS");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.YOUR_IMAGE_NAME);

onCreate 之外使用此按钮将 Click Listener 设置为此按钮

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
           

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

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

activity_youractivity.xml布局中使用这个,

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/AppbarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/Toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>

styles.xml中使用这个,

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
</resources>

build.gradle (app)中使用这个,

implementation 'com.google.android.material:material:1.1.0'

希望这对您有所帮助。随时要求澄清...

只需使用Toolbar中的setNavigationIcon方法即可:

    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.xxxx);
    setSupportActionBar(toolbar);