Reputation: 1330
I have a problem with developing an app for both tablets and smartphones with fragments.
When app is executed on smartphone, I show a fragment with a list (categories). When clicking on an item, I start a new activity that holds a ViewPager that inflates Fragments with another list (detail).
When app is executed on tablet I have a layout with two fragments inside. The left one is the categories list and the right one is the detail list.
Up to here there's no problem, but when setting onOptionsItemSelected I have problems.
When executing app on smartphone, everything is working well. This works:
Activity containing ViewPager
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icShare:
sharePortal();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
Fragment inflated by ViewPager
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icFavourite:
Utils.setFavouritePortal(mContext, mPortal);
getActivity().invalidateOptionsMenu();
return true;
case R.id.icShowFavourites:
showFavouriteArticles();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
But when executing the app in tablet, onOptionsItemSelected is not called. This is the code:
Fragment containing ViewPager
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icShowFavourites:
Log.e("asdf", "asdfasdf - test tablet");
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
Fragment inflated by ViewPager
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icFavourite:
Utils.setFavouritePortal(mContext, mPortal);
getActivity().invalidateOptionsMenu();
return true;
case R.id.icShowFavourites:
showFavouriteArticles();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
The only difference is that when executing on smartphone, the first onOptionsItemSelected is hold by an Activity and in tabled is hold by a fragment. I also tried to execute the onOptionsItemSelected from the Activity containing the fragment that contains the ViewPager inflating other fragments with no luck.
How can I get it working?
Thank you in advance!
Upvotes: 0
Views: 1657
Reputation: 357
Try to put setHasOptionsMenu(true);
inside the fragment where you want onOptionsItemSelected()
to be called.
Upvotes: 2
Reputation: 8050
The fragment should call setHasOptionsMenu(true)
, and should implement onCreateOptionsMenu()
and onOptionsItemSelected()
.
Upvotes: 0