I would like to know after all my time-wasting, how to add custom buttons to the toolbar/activitybar? If someone have the answer, can please he/she post it to me...
Asked
Active
Viewed 1.0k times
3 Answers
2
The toolbar is a ViewGroup, you can add any layout inside it. In the below-given example, I am using the LinearLayout.
layout.xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:titleTextColor="#FFFFFF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right">
<Button
android:id="@+id/toolbar_overflow_menu_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
In java, you can access the Button
as
Button button = (Button) findViewById(R.id.toolbar_overflow_menu_button);
Making the button clickable in Java class
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});

Dharmendra Pratap Singh
- 1,332
- 1
- 11
- 22
-
due to android:layout_width="match_parent" title remains under linearLayout – Ilker Baltaci Aug 22 '17 at 12:45
-
I would suggest using TextView inside the LinearLayout to set the title so that they are aligned and the boundary is properly set. – Dharmendra Pratap Singh May 03 '20 at 12:46
1
Since Toolbar
subclass of ViewGroup
so you can put what ever views inside it
<android.support...Toolbar
android:layout_width=".."
android:layout_height=".."
..
...>
<Button
android:layout_width=".."
android:layout_height=".."
...
...
/>
</android....Toolbar>

Moh'd Awad
- 1,758
- 1
- 12
- 22
0
You can make custom toolbar like below and add any View to your Toolbar
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:id="@+id/toolbar_title" />
</android.support.v7.widget.Toolbar>

Hosein Hamedi
- 322
- 4
- 16