I want to implement menu in fragment class. The fragment works fine and there is not error but there is no menu shown in the fragment. I am implementing the class in the following way
public class FilesFragment extends Fragment {
public FilesFragment() {
// Required empty public constructor
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_files, container, false);
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
inflater.inflate(R.menu.files_menu,menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_setting){
Toast.makeText(getActivity(),"setting clicked",Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
}
and this is the xml file of files_menu in menu folder.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_setting"
android:title="settings"
app:showAsAction="never"/>
<item
android:id="#+id/aobut"
android:title="About"
app:showAsAction="never"
/>
</menu>
The above code is not showing the menu at all. How do menu is implemented in the fragment?
You can populate the menu in any view without any complexity. Use the following code and enjoy.
any View can be a button , imageView or any other else in which you want to inflate this menu. No need to add menu in xml. Just do in java
PopupMenu popup = new PopupMenu(context, any View);
popup.inflate(R.menu.files_menu );
popup.setOnMenuItemClickListener(item -> {
int id = item.getItemId();
if (id == R.id.action_setting) {
// do stuff
} else if (id == R.id.aobut) {
//
}
return true;
});
popup.show();
Related
I'm working with a toolbar that has a search action button, it was used to work and suddenly it stopped showing it to me. This is my code:
In my menu folder
menu_feed.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
android:title="#string/action_search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always|collapseActionView" />
</menu>
This is the class where i call that item and inflates it into the toolbar
FeedFragment.class
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_feed, container, false);
setupToolbar(v);
return v;
}
private void setupToolbar(View v) {
AppCompatActivity activity = (AppCompatActivity) getActivity();
toolbar = (Toolbar) v.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupRV();
mFeedPostsPresenter = new FeedPostsPresenterImpl(this);
}
private void setupRV() {
mFeedPostsRV = (RecyclerView) getView().findViewById(R.id.feed_posts_list);
mFeedPostsRV.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mFeedPostsRV.setLayoutManager(layoutManager);
RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
itemAnimator.setAddDuration(1000);
itemAnimator.setRemoveDuration(1000);
mFeedPostsRV.setItemAnimator(itemAnimator);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_feed, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_search){
Intent i = new Intent(getActivity(), SearchUsersActivity.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
For some reason I don't know why this search button disappeared from my toolbar and I can't see it again, this is my output from menu_feed.xml:
And in runtime inside my app there is no action_search:
The "collapseActionView" allows the button to be shown but as a widget. This button can be dynamic, like a search button that expands. Check this: Documentation. Try deleting this in your menu_feel.xml
The overflow menu icon is not showing in my Activity with a tab style navigation layout. The tabs are implemented using a ViewPager, Fragments and a TabLayout.
The overflow menu is showing in my Activities which do not have tabs which makes me think the overflow menu not showing is something to do with my implementation of the tabs navigation.
Here is a basic model of my Activity:
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_layout);
initTabLayout();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_layout, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
public void initTabLayout(){
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setTabTextColors(Color.parseColor("#e3e8e7"), Color.parseColor("#7e7e7e"));
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setOffscreenPageLimit(4); //this stops the tabs from losing their data when you change tabs
//sets up adapter that contains the scrolling pageAdapter and the fragment which is displayed
viewPager.setAdapter(new ActivityTabAdapter(getSupportFragmentManager(),
MainActivity.this));
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
And here is my FragmentPagerAdapter implementation:
public class ActivityTabAdapter extends FragmentPagerAdapter {
#Override
public Parcelable saveState() {
return super.saveState();
}
final int PAGE_COUNT = 4;
private String tabTitles[] = new String[]{"tab1", "tab2", "tab3", "tab4"};
private Context context;
public ActivityTabAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
return PageFragment.newInstance(position + 1);
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
//These are fragments which hold the layouts of the tabs
public static class PageFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
Context mContext;
View tab1rootView;
View tab2Rootview;
View tab3RootView;
View tab4RootView;
Tab1 tab1;
Tab2 tab2;
Tab3 tab3;
Tab4 tab4;
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
MenuInflater mInflater;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
mInflater = inflater;
inflater.inflate(R.menu.menu_layout, menu);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
mInflater.inflate(R.menu.menu_layout, menu);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mContext = getActivity();
mPage = getArguments().getInt(ARG_PAGE);
Log.v("whichFrag", "" + getArguments().getInt(ARG_PAGE));
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
tab1rootView = inflater.inflate(R.layout.tab1_layout, container, false);
tab2Rootview = inflater.inflate(R.layout.tab2_layout, container, false);
tab3RootView = inflater.inflate(R.layout.tab3_layout, container, false);
tab4RootView = inflater.inflate(R.layout.tab4_layout, container, false);
int i = getArguments().getInt(ARG_PAGE);
if (getArguments().getInt(ARG_PAGE) == 1) { //if 1, then we inflate tab1rootView layout
tab1 = new Tab1(tab1rootView, getActivity());
tab1.initCardViews1();
return tab1rootView;
} else if (getArguments().getInt(ARG_PAGE) == 2) { //if 2, then we inflate tab2Rootview layout
tab2 = new Tab2(tab2Rootview, mContext);
return tab2Rootview;
} else if (getArguments().getInt(ARG_PAGE) == 3) { //if 3, then we inflate tab3RootView layout
tab3 = new Tab3(tab3RootView, mContext);
return tab3RootView;
} else { //if 4, then we inflate tab4RootView layout
tab4 = new Tab4(tab4RootView, mContext);
return tab4RootView;
}
}
}
}
Here is my xml 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="com.example.heavymagikhq.profilepageofficial.profileEditorJava.Profile_info_editor">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
<item
android:id="#+id/action_settings2"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"
android:visible="true" />
<item
android:id="#+id/action_settings1"
android:orderInCategory="100"
android:title="#string/action_settings"
android:icon="#drawable/ic_action_menu"
app:showAsAction="never"
android:visible="true" />
</menu>
I have looked at other answers on stackoverflow but I couldn't find the answer.
I'll post more information if you need it.
Thanks in advance.
Okay, so I figured it out and the answer is simple. I didn't need to use setHasOptionsMenu(true); in any of the Fragments' lifecycle stages, and you must in my experience have app:showAsAction="never"as an xml attribute on your at least one of your xml menu items.
If you're extending AppCompatActivity in the Activity which implements the TabLayout and you're also using a Toolbar in that Activity then get a reference to your Toolbar and call this.setSupportActionBar(toolbar); while passing in your Toolbar as a parameter.
It should look like so:
Toolbar toolbar = (Toolbar) findViewById(R.id.editProfileToolbar);
this.setSupportActionBar(toolbar);
And call this in the onCreate() method of your Activity.
Try moving setHasOptionsMenu to Oncreate() method of the fragment and use it only once.Also don't inflate the menu twice.Inflate once in OncreateOptionsMenu() and change the visibility of the items in OnPrepareOptionsMenu() instead of inflating again.
I have implemented Navigation drawer given in the Android Studio 1.5.1.
I have 5 navigation drawer items with a fragment to each of them. Each Fragment has Share method (Not common).
Inside 1st Navigation drawer item's fragment lets say OldStory Fragment, I am having Swipe view with Viewpager consisting 3 fragments with FragmentStatePagerAdapter. It has Share method.
Problem
- Share Method from Story Fragment is getting called every time even when other fragment is shown on screen. After debugging I came to know that method from Story fragment is getting called.
- If I disable OldStory Fragment then everything works fine.
I am unable to solve this problem. I read so many Question/answers but they are related to Activity and Fragment methods. Please help me to solve this problem.
Note - OldStory fragment has inner class that extends FragmentStatePagerAdapter class. This class creates Many Story Fragments. Other implementation is same.
public class OldStory extends Fragment {
private StoryPagerAdapter storyPagerAdapter;
private InfiniteViewPager viewPager;
SharedPreferences sharedPreferences;
private int TotalCount;
public OldStory() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Notify the system to allow an options menu for this fragment.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_old_story, container, false);
viewPager = (InfiniteViewPager) rootView.findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(0);
sharedPreferences = getActivity().getSharedPreferences(Startup.PreferenceSETTINGS, Context.MODE_PRIVATE);
TotalCount = sharedPreferences.getInt(Startup.StoryCount, 4);
storyPagerAdapter = new StoryPagerAdapter(getFragmentManager());
PagerAdapter wrappedAdapter = new InfinitePagerAdapter(storyPagerAdapter);
viewPager.setAdapter(wrappedAdapter);
viewPager.setCurrentItem(TotalCount-1);
return rootView;
}
public class StoryPagerAdapter extends FragmentStatePagerAdapter {
public StoryPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return Story.newInstance(position+1);
}
#Override
public int getCount() {
return TotalCount;
}
}
}
Story Fragment method Implementation -
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.story, menu);
getActivity().getMenuInflater().inflate(R.menu.main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Refresh:
// We make sure that the SwipeRefreshLayout is displaying it's refreshing indicator
if(!visiblity) {
if (!RefreshLayout.isRefreshing()) {
ErrorLayout.setVisibility(View.GONE);
RefreshLayout.setRefreshing(true);
}
// Start our refresh background task
initiateRequest(Today);
}
return true;
case R.id.Share:
//InShort = sharedPreferences.getString(Startup.InShort, null);
Toast.makeText(getContext(), "Stories", Toast.LENGTH_SHORT).show();
if (InShort!= null && !InShort.isEmpty())
{
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hi From Story");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
MainActivity used for switching fragments.
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displayView(item.getItemId());
return true;
}
//method to replace Views in ID = content_frame in content_main
public void displayView(int viewID)
{
fragment = null;
title = getString(R.string.app_name);
switch (viewID)
{
case R.id.nav_frag0:
fragment = new OldStory();
title = getString(R.string.story);
viewIsAtHome = true;
break;
case R.id.nav_frag1:
fragment = new Fragment1();
title = getString(R.string.fragment1);
viewIsAtHome = false;
break;
case R.id.nav_frag2:
fragment = new Fragment2();
title = getString(R.string.fragment2);
viewIsAtHome = false;
break;
case R.id.nav_frag3:
fragment = new Fragment3();
title = getString(R.string.fragment3);
viewIsAtHome = false;
break;
case R.id.nav_frag4:
fragment = new Fragment4();
viewIsAtHome = false;
title = getString(R.string.fragment4);
break;
case R.id.nav_share:
fragment = new Fragment5();
title = getString(R.string.fragment5);
viewIsAtHome = false;
break;
}
if (fragment != null)
{
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,fragment);
ft.commit();
}
//set the toolbar title
if(getSupportActionBar() != null)
{
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
I am not sure if it is really the answer to your question, but I noticed one error in your code:
storyPagerAdapter = new StoryPagerAdapter(getFragmentManager());
will not work correctly becasuse you need to use getChildFragmentManager() to manage fragments within fragments.
I was trying to reproduce your issue and wrote this app, which as I understood from the question is copying your app's behaviour:
I've uploaded the source code for it into my Dropbox - feel free to check it out
As you can see, the fragments handle Share button clicks properly.
There's always a chance, that I didn't fully understand your question, but here's how I've done it:
All fragments inflating this menu (but with different onOptionsItemSelected):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
app:showAsAction="always"
android:title="Share" />
</menu>
My SubFragment class (the one I'm using inside ViewPager) in FragmentA:
public class SubFragment extends Fragment {
String msg;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.subfragmnet, container, false);
setHasOptionsMenu(true);
rootView.findViewById(R.id.subfragmentFrameLayout).setBackgroundColor(getArguments().getInt("background"));
msg = getArguments().getString("msg");
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.nav_share) {
Snackbar.make(getView(), "Hello from SubFragment " + msg, Snackbar.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
FragmentA, the first Fragment, which hosts ViewPager and nested Fragments:
public class FragmentA extends Fragment {
PagerAdapter pagerAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
Bundle bundle1 = new Bundle();
bundle1.putInt("background", Color.RED);
bundle1.putString("msg", "page 1");
Bundle bundle2 = new Bundle();
bundle2.putInt("background", Color.YELLOW);
bundle2.putString("msg", "page 2");
Bundle bundle3 = new Bundle();
bundle3.putInt("background", Color.BLUE);
bundle3.putString("msg", "page 3");
Fragment[] fragments = {
Fragment.instantiate(getContext(), SubFragment.class.getName(), bundle1),
Fragment.instantiate(getContext(), SubFragment.class.getName(), bundle2),
Fragment.instantiate(getContext(), SubFragment.class.getName(), bundle3),
};
if (pagerAdapter == null) {
pagerAdapter = new PagerAdapter(getChildFragmentManager(), fragments);
}
ViewPager viewPager = (ViewPager)rootView.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
return rootView;
}
}
FragmentB (and pretty much the same FragmentC):
public class FragmentB extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
return inflater.inflate(R.layout.fragment_b, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_fragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.nav_share) {
Toast.makeText(getContext(), "Hello from Fragment B", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
Hosting Activity is standard NavigationDrawer Activity with is switching Fragments on Drawer's item click.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
....
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentA.class.getName())).commit();
}
...
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentA.class.getName())).commit();
} else if (id == R.id.nav_gallery) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentB.class.getName())).commit();
} else if (id == R.id.nav_slideshow) {
getSupportFragmentManager().beginTransaction().replace(R.id.container, Fragment.instantiate(this, FragmentC.class.getName())).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Let me know, if I understood your question properly!
Anyway, I hope, it helps.
I'm using fragments and I have a menu item in one of my fragments. The fragment that uses the menu item is called when an item in the List View is clicked. When the fragment with the menu item is called, and then I change the tab, the menu item is still there. I want the menu item to only show in the one fragment only.
Here is the code for Tab 1
public class Tab2Fragment extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().setTitle("Tab 2");
initView();
}
private void initView() {
((TextView)getView().findViewById(R.id.tab_text)).setText("Tab 2");
Button button = (Button) getView().findViewById(R.id.tab_btn);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
replaceFragment();
}
});
}
private void replaceFragment() {
((BaseContainerFragment)getParentFragment()).replaceFragment(new Tab2AddOnFragment(), true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
and Here is the code for Tab 3 which has the List View
public class Tab3Fragment extends ListFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] values = new String[] { "Ang na Ang na", "Sulakihin", "Somaskidot", "Moko Moko"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
getActivity().setTitle("Tab 3");
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
switch(position){
case 0:
// Create new fragment and transaction
FragmentTransaction transaction = getFragmentManager().beginTransaction();
replaceFragment();
transaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
// Commit the transaction
transaction.commit();
break;
default:
}
}
private void replaceFragment() {
((BaseContainerFragment)getParentFragment()).replaceFragment(new FragmentInListView(), true);
}
}
and here is the code for the fragment with the menu item
public class FragmentInListView extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActivity().setTitle("Fragment Called in Tab 3(List View)");
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.tab_fragment,
container, false);
TextView tv= (TextView) view.findViewById(R.id.tab_text);
tv.setText("Fragment in List View");
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
inflater.inflate(R.menu.travel_tips_expanded, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
and here is the code for the menu of the fragment with a menu item
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings"/>
<item
android:id="#+id/favorite"
android:showAsAction="always"
android:title="favorite"/>
Here is an image of the Fragment called when an item in the List View is clicked. And it contains the menu item.
http://s904.photobucket.com/user/fookywooky/media/tab4_zps30944a6e.png.html
And here is an image of the Fragment called when "Tab 2" is selected. As you can see, the menu item is still there but i don't want it to be there. Also, this is the case even if you click Tab 1 and Tab 3. The menu item is still there.
http://s904.photobucket.com/user/fookywooky/media/tab5_zps285c8314.png.html
Please help. Thanks in advance.
In order to accurately determine when to show the Fragment menu, your Activity needs some indication as to which Fragment is visible and current. You can accomplish this with the setMenuVisibility() and setUserVisibleHint() methods. In your OnTabChanged() callback, set the menu visibility and user visible hint to false in the previously selected Fragment and true in the currently selected Fragment.
I like to change menu when the activity is changed. I have MainActivity.java with activity_main.xml menu. Then I have MyDetailFragment.java with detail_view_menu.xml. The MainActivity menu is inflated in the onCreateOptionsMenu of MainActivity.java as
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.activity_main, menu);
return (super.onCreateOptionsMenu(menu));
}
It works fine. When one of the items is tapped and the MyDetailFragment.java is loaded, I like to display detail_view_menu.xml. How I implement is
public class MyDetailsFragment extends Fragment {
TrackerInfo trackerInfo;
public MyDetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.my_details_fragment, container, false);
setHasOptionsMenu(true);
TextView displayText = (TextView) view.findViewById(R.id.details);
displayText.setText(trackerInfo.getIdnumber());
return view;
}
public void retrieveData(TrackerInfo tracker){
trackerInfo = tracker;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.detail_view_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.track:
return (true);
case R.id.view_history:
return (true);
}
return (super.onOptionsItemSelected(item));}}
But the problem is that the menu is still the same activity_main menu and never changed. What could be the problem?
You need to super call the same method.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.detail_view_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
Once I had issue when the new menu items where appended to the menu. So I resolve it with removing all menu items before inflating new ones.
Like this:
public static void emptyFragmentOptionsMenu(Menu menu){
if(menu==null)return;
for(int i=0; i < menu.size(); i++)
menu.removeItem(menu.getItem(i).getItemId());
}
Cheers,
Edit: How I used the method:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
emptyFragmentOptionsMenu(menu);
inflater.inflate(R.menu.detail_view_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
First: you should have an onCreate() method above your onCreateView() and there you set setHasOptionsMenu(true);
Second: you need to use super.onCreateOptionsMenu(menu, inflater); after the inflater in your onCreateOptionsMenu().
Third: you have just duplicated your question that you originally posted here. Please don't do that in the future. I have provided you with additional details on that question then you switched on this one. Next time just edit your original question. Otherwise you might just sabotage yourself and become annoying for those trying to help you.
Do this:
public class MyDetailsFragment extends Fragment {
TrackerInfo trackerInfo;
public MyDetailsFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true); // this should go here not in onCreateView();
// ....
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.my_details_fragment, container, false);
TextView displayText = (TextView) view.findViewById(R.id.details);
displayText.setText(trackerInfo.getIdnumber());
return view;
}
public void retrieveData(TrackerInfo tracker){
trackerInfo = tracker;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.detail_view_menu, menu);
super.onCreateOptionsMenu(menu, inflater); // you need to call super
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.track:
return (true);
case R.id.view_history:
return (true);
}
return (super.onOptionsItemSelected(item));
}
}