Reputation: 1911
I have two fragment activities and one fragment. Here's how the app logic looks like:
FragmentActivity A ==> Fragment B ==> FragmentActivity C.
FragmentActivity A is the parent activity of fragment B and has an options menu that shows correctly.Fragment B contains a listview. When a list item is clicked on fragment B,its details are displayed in FragmentActivity C.Now i want to display an options menu inside C in the actionBar.However, the menu is only displayed after the menu button is clicked.I want it as an actionbar action.
Here is the code for Activity C:
public class LatestDetailsFragment extends FragmentActivity implements
OnItemClickListener {
public LatestDetailsFragment() {
photoImages = new ImageItem();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_latestdetails);
gallery.setOnItemClickListener(this);
// setHasOptionsMenu(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.details_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.contact:
ContactOwnerFragment contactFragment = new ContactOwnerFragment();
Bundle bundle = new Bundle();
bundle.putString(KEY_PHONE, phone);
contactFragment.setArguments(bundle);
contactFragment.show(getSupportFragmentManager(), "contact");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And the menu:
<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"
tools:context="be.hcpl.android.example.MainActivity" >
<item
android:id="@+id/contact"
android:icon="@drawable/ic_action_call"
android:orderInCategory="100"
android:title="@string/contact"
app:showAsAction="ifRoom|withText">
</item>
I cannot use setHasOptionsMenu(true);
on the activity because it raises an error,I don't know why. I want to display an icon on the actionbar.
Upvotes: 0
Views: 2118
Reputation: 5591
You need to use menu.clear()
before inflating menus.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.clear();
getMenuInflater().inflate(R.menu.details_fragment_menu, menu);
return super.onCreateOptionsMenu(menu);
}
From the Documents
public abstract void clear () Remove all existing items from the menu, leaving it empty as if it had just been created.
Upvotes: 1