How to create button in Action bar in android [duplicate]
In your activity class, override the following methods if they are not there by default:
// create an action bar button@Overridepublic boolean onCreateOptionsMenu(Menu menu) { // R.menu.mymenu is a reference to an xml file named mymenu.xml which should be inside your res/menu directory. // If you don't have res/menu, just create a directory named "menu" inside res getMenuInflater().inflate(R.menu.mymenu, menu); return super.onCreateOptionsMenu(menu);}// handle button activities@Overridepublic boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.mybutton) { // do something here } return super.onOptionsItemSelected(item);}
mymenu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"><item android:id="@+id/mybutton" android:title="" app:showAsAction="always" android:icon="@drawable/mybuttonicon" /></menu>
If you want to customize UI of your ActionBar, then you can use Toolbar as ActionBar. Here are the steps to do the same :
Add below code as a child of AppBarLayout in your activity layout xml.
<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="1"> <TextView android:id="@+id/title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="ActionBar Title"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </android.support.v7.widget.Toolbar>
Make your Toolbar as ActionBar by adding the below code in your Activity onCreate() method.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);getSupportActionBar().setDisplayHomeAsUpEnabled(true);
In AndroidManifest.xml, add following theme to your activity:
android:theme="@style/AppTheme.NoActionBar"
In styles.xml add following code:
<style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item></style>
Here are the steps to get it done:
Create a menu in res/menu (Name it my_menu.xml)
<menu xmlns:android="http://schemas.android.com/apk/res/android"><item android:id="@+id/action_cart" android:icon="@drawable/cart" android:orderInCategory="100" android:showAsAction="always"/> </menu>
Override onCreateOptionsMenu and inflate the menu
@Overridepublic boolean onCreateOptionsMenu(Menu menu) {MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.my_menu, menu);return true;}