I have a ListFragment and I have to add a menu. This is my code: listuser_menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/any_option"
android:title="In Context Menu" />
</menu>
My ListFragment:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View mFooterView;
// We need to use a different list item layout for devices older than Honeycomb
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
android.R.layout.simple_list_item_activated_1:android.R.layout.simple_list_item_1;
if(getListAdapter()==null){
// init adapter
adapter=new UserArrayAdapter(getActivity(),
MOBILE_OS);
}
else{
adapter.notifyDataSetChanged();
}
// set adapter
registerForContextMenu(getListView());
setListAdapter(adapter);
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo){
menu.clear();
super.onCreateContextMenu(menu, v, menuInfo);
final MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.listuser_menu, menu);
}
But i can't see my menu..why? How register option menu selected? Thanks!
Use this sample code inside your MainActivity.
Yes, you can add menu to ListFragment, add below code into your ListFragment
And after that add Fragment version onCreateOptionsMenu() method, as given below
@ Sherlock Yiu forgot to add "super.onActivityCreated(savedInstanceState);" into onActivityCreated() method, rest is same.
Also dont forgot to add "android-support-v4.jar" into project libraries.
Above code snippet is working for me.
Adding menus to fragment is possible, use the following code in your Fragment:
}
Using setHasOptionsMenu will allow your fragment to show a menu.