I was late for an answer, but I think this is another solution that is not mentioned here, so I submit.
Step 1: Make the xml menu you want to add, as if I should add a filter action to my action bar to create an xml filter.xml . The main line to be noted is android: orderInCategory , this will show the action icon at the beginning or at the end, wherever you want to show. Another thing to note is the value, if the value is less than it will be displayed at the beginning, and if the value is larger, then it will be displayed last.
filter.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" > <item android:id="@+id/action_filter" android:title="@string/filter" android:orderInCategory="10" android:icon="@drawable/filter" app:showAsAction="ifRoom" /> </menu>
Step 2: In onCreate (), the fragment method just placed the line below, as indicated, which is responsible for calling onCreateOptionsMenu (menu menu, MenuInflater blower) , as in Activity .
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); }
Step 3: Now add the onCreateOptionsMenu method, which will be redefined as:
@Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.filter, menu);
Step 4: Now add the onOptionsItemSelected method, with which you can implement the logic, no matter what you do when you select the added action icon from the actionBar :
@Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id == R.id.action_filter){
Pankaj Aug 11 '15 at 7:38 2015-08-11 07:38
source share