I want to add a clickable icon/button to the left of the title in the action bar . How to do it? Following is the code with which I have added search and setting icon to the action bar. They appear on the right. But i want to add a new icon to the left of title. How to do it? XML :
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.home.activities.TransactionSearchActivity">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
<item android:id="@+id/action_setting"
android:title="categories"
android:icon="@drawable/icon_settings_h"
app:showAsAction="always"
/>
MAIN ACTIVITY
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
Recommended way
Handle icon click event
I always like to put a AppBarLayout that I can control the way the toolbar appears
That way a can put more elements and arrange them like I want. In this case insert a left icon to close the activity by a fragment.
So in the fragment a do this
The result will be something like this:
The action "SALVAR" i put via inflat menu
Menu XML layout src/menu/menu_add_plan_tour.xml
And do not forget to use setHasOptionsMenu(true) to enable the menu.
You can show an icon at the left side using the following code.
But it wont be clickable. To make a clickable icon at the left, you need to use Toolbar instead of an action bar.
As this is updated era of Android, You must go for Toolbar so that you can do any kind of customization with the help of xml. Instead of using menu i would suggest to use toolbar
And through code you can handle event
You can do the following:
1- create your file_name.xml then Add
Toolbar
.2- add
RelativeLayout
inside theToolbar
's tag.3- add your views i.e.(
ImageButton
,TextView
,...)Note: The
TextView
you are adding is the title ofToolbar
.Sample Code: file_name.xml
Output:
One thing is that by default title and app icon set into the left and other than icons sent into the right side. If you want to add your icons into the left side there is a way to them into to left side which is:
step 1. create a custom layout which having search, setting icon and your title as you want.
step 2. create a toolBar layout like:
step 3. inflate your custom layout into the toolbar like: