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:
-
Open your Android project in Android Studio and navigate to the activity where you want to add the button.
-
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" />
-
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'sonCreate
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 } }); }
-
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.