Android studio add button to toolbar of new activity

To add a button to the toolbar of a new activity in Android Studio, you can follow these steps:

  1. Open your Android project in Android Studio and navigate to the activity where you want to add the button.

  2. Open the activity_main.xml file (or the name of your activity's layout file) and add the following code inside the <LinearLayout> or <RelativeLayout> tag:

    
    <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:theme="@style/ThemeOverlay.AppCompat.ActionBar">
    
     <ImageButton
         android:id="@+id/button_toolbar"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/ic_add"
         android:tint="@color/white" />
``` This code adds a `Toolbar` with an `ImageButton` inside it. You can customize the appearance of the button by changing the `android:src` attribute to point to a different drawable resource, and the `android:tint` attribute to change the color of the button.
  1. In your activity's Java code, you need to inflate the layout and set the Toolbar as the action bar. Add the following code to your activity's onCreate method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
    
     Toolbar toolbar = findViewById(R.id.toolbar);
     setSupportActionBar(toolbar);
    
     // Get the button from the toolbar
     ImageButton button = findViewById(R.id.button_toolbar);
    
     // Set a listener for the button
     button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             // Handle the button click event
         }
     });
    }
  2. Run your app on a device or emulator to see the button in the toolbar.

Note: Make sure you have the androidx.appcompat:appcompat library in your project's build.gradle file and that you have imported the androidx.appcompat.widget.Toolbar class in your activity's Java code.

Also, you can use app:popupTheme attribute in the Toolbar to set the theme of the popup menu that appears when the button is clicked.

<androidx.appcompat.widget.Toolbar
   ...
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
   ...>

This will set the theme of the popup menu to a light theme. You can customize the theme to fit your app's design.