I am having a tablayout, navigationdrawer and toolbar in an activity.
Added 3 fragments to viewpager and added viewpager to tablayout:
Code snippet of my activity:
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
Now in each fragment I have to display different options in toolbar:
So I tried to access the toolbar in my fragment like this:
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
_context = getActivity();
mainView = inflater.inflate(R.layout.frag1, container, false);
mToolbar =(Toolbar) mainView.findViewById(R.id.app_bar);
mToolbar.setTitle("");
toolbarTitle = (TextView) getActivity().findViewById(R.id.toolbar_title);
toolbarTitle.setText("Fragment1");
toolbarTitle.setSelected(true);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(mToolbar);
}
Inflated the required menu in onCreateOptionsMenu(Menu menu, MenuInflater inflater)
but not inflating as required the menu in toolbar. How can we change the toolbar options in Fragment.
This is working for me. This is all I have in onCreate. (Refreshable is an interface of my own).
public class SummaryFragment extends Fragment implements Refreshable {
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
And this is where I inflate the menu.
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.save, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
{
File csvFile = saveResults();
etc...
It's gone now, but I even had a different menu in my MainActivity and the two were both present when my Summary tab was active.
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
My main_activity have 2 fragments -> Parent and Child as follow :
https://imgur.com/ws9BRWR
each fragment should have their own actionbar and their own menu.
my question are : why is the menu that supposedly shown in child fragment mixed together into the parent fragment?
Child-Menu-1 and Child-Menu-2 supposed to be inside menu in child fragment
this is what i have done :
fragmentParent :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_parent, container, false);
setHasOptionsMenu(true);
Toolbar myToolbar = (Toolbar) view.findViewById(R.id.tb_parent);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("PARENT");
//((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_parent, menu);
}
fragmentChild :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_child, container, false);
setHasOptionsMenu(true);
Toolbar myToolbar = (Toolbar) view.findViewById(R.id.tb_child);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("CHILD");
//((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_child, menu);
}
what i have tried already :
move the getSupportActionBar into onViewCreated <--- same result
move the inflate to onPrepareOptionsMenu <--- same result
i noticed that if i remove the menu from the parent fragment, the menu on the child show up correctly, problem only if i try to load each with their own menu.
when i debug the apps, the sequence called are :
calling child fragment onCreateView
calling parent fragment onCreateView
calling child onCreateOptionsMenu
calling parent onCreateOptionsMenu
so i'm suspecting the problem is in the onCreateOptionMenu where the inflater inflate the wrong fragment.
i already do a lot of searching inside SO and google, but no question seems similar to my case.
thank you very much in advance!!
==========================================================================
further examination and testing... so i commented out the creating of the toolbar from the parent fragment :
fragmentParent :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_parent, container, false);
setHasOptionsMenu(true);
//Toolbar myToolbar = (Toolbar) view.findViewById(R.id.tb_parent);
//((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
//((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("PARENT");
//((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_parent, menu);
}
fragmentChild :
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_child, container, false);
setHasOptionsMenu(true);
Toolbar myToolbar = (Toolbar) view.findViewById(R.id.tb_child);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("CHILD");
//((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_child, menu);
}
Result :
https://imgur.com/wYVdsvH
all menu item show up in the child fragment, why is the parent fragment onCreateOptionMenu getting called while there's no toolbar is declared?
i'm hitting wall here :(
Have you tried calling invalidateOptionsMenu() after you've added or replaced the Fragment?
I found the answer from this link:
Set menus for multiple toolbars on android
If we running multiple toolbar menu within 1 activity (even in different fragment in my case)
for the first toolbar, inflate is from onCreateOptionsMenu(), and callback is from onOptionsItemSelected()
for the second toolbar, via we need to inflate the second menu toolbar and set the callback manually:
toolbar2 = (Toolbar) findViewById(R.id.tool_bar_bottom);
toolbar2.inflateMenu(R.menu.bottom_menu);//changed
toolbar2.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem arg0) {
if(arg0.getItemId() == R.id.item_id){
}
return false;
}
});
Thank you #skadoosh.
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 looking at a guide on how to use TabLayout. This is how they show to attach the PagerAdapter class.
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity.this));
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
However, their TabLayout is in an Activity, and mine is in a Fragment. I'm having trouble adapting their code to my use case, because I don't fully understand the practical differences between activities and fragments. Right now, when I try and swipe between tabs, nothing happens. Here is my code:
public class CandidateListFragment extends Fragment {
public static final String TAG = "candidates";
#InjectView(R.id.tabLayout) TabLayout tabLayout;
public CandidateListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_candidatelist, container, false);
initInstances(v);
return v;
}
private void initInstances(View v){
//TODO: Change to support below API level 21
getActivity().findViewById(R.id.toolbar_actionbar).setElevation(R.dimen.toolbar_candidatelist_elevation);
ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
viewPager.setAdapter(new TabsFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
getActivity()));
ButterKnife.inject(this, v);
tabLayout.setupWithViewPager(viewPager);
}
#Override public void onDestroyView() {
super.onDestroyView();
ButterKnife.reset(this);
}
I figured it out!!!
I had my xml layout file for the fragment set to RelativeLayout instead of LinearLayout, so my ViewPager wasn't on the screen, which meant I couldn't swipe. It's the simple mistakes that get me