Add Icon to the left of the title in the action bar in android
You can do the following:
1- create your file_name.xml then Add Toolbar
.
2- add RelativeLayout
inside the Toolbar
's tag.
3- add your views i.e.(ImageButton
,TextView
,...)
Note: The TextView
you are adding is the title of Toolbar
.
Sample Code: file_name.xml
<android.support.v7.widget.Toolbar
android:id="@+id/products_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimaryDark"
app:layout_collapseMode="pin"
app:titleTextColor="@android:color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Title"
android:gravity="center"
android:textColor="@android:color/white"
android:textSize="20dp"
android:textStyle="bold"
android:layout_alignParentStart="true"/>
<ImageButton
android:id="@+id/toolbar_button"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@drawable/ic_icon_24dp"
style="@style/Widget.AppCompat.Button.Borderless"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
Output:
Recommended way
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_settings_24dp);// set drawable icon
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Handle icon click event
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(this, "click..!!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}