Q:

how to use Buttons on action bar With Fragments?

i want to add button on the actionbar of a fragment.But i'm getting error on this code given below. 
this is my Fragment code where i want to add button on actionbar of this tab
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
         final View view = inflater.inflate(R.layout.credit_main, container, false);
return view;
    }
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.search_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // action with ID action_refresh was selected
            case R.id.search:
                Toast.makeText(getActivity(), "Refresh selected", Toast.LENGTH_SHORT)
                        .show();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}

here error is getMenuInflater(); cannot resolve 

A:

Step 1 : Make a xml of menu which you want to add.
<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/item1"
        android:title="@string/filter"
        android:orderInCategory="10"
        android:icon="@drawable/ic_launcher"
        app:showAsAction="ifRoom" />
</menu>

Step 2: 
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

Step 3:
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.search_result, menu);
    }

Step 4:
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.item1){
            //What you want(Code Here) 
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

A:

You have to call setHasOptionsMenu(true) to make it work.
Do something like:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

and then use the onCreateOptionsMenu() method with the inflater.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    // Inflate the menu items for use in the action bar
    inflater.inflate(R.menu.search_menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

Take a look at setHasOptionsMenu() and onCreateOptionsMenu().

