Abdul.Moqueet Abdul.Moqueet - 1 month ago 16
Android Question

Implement 3 dot menu to a fragment

Hi guys i want to create 3 dot action bar menu at fragment level, the condition is i want to show that menu at just 1 fragment not on all and if i make them at my main activity, Then i can't hide them so that's why i need to make them at fragment level. so, far i have tried this code on my fragment

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.sync:
Toast.makeText(this, "Sync data...", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}


But its saying the method "onCreateOptionsMenu" doesn't override from its super class.

It look like I'm miss something very basic, don't know what it is.

Thanks

Answer

Try like this

menu_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>

OnCreate Method of fragment

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

onCreateOptionsMenu

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_filter.xml, menu);  // Use filter.xml from step 1
    }

onOptionsItemSelected

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_filter){
            //Do whatever you want to do 
            return true;
        }

        return super.onOptionsItemSelected(item);
    } 

I hope it might help you !