Search code examples
javaandroidandroid-toolbarandroid-styles

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


I want to add an **add-button on the left side of my android app toolbar


Solution

  • In YourActivity.java use this,

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

    Use this outside of onCreate to set Click Listener to this Button

     @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);
        }
    }
    

    In activity_youractivity.xml layout use this,

    <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>
    

    In styles.xml use this,

    <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>
    

    In build.gradle (app) use this,

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

    Hope this helps. Feel free to ask for clarifications...