I'm not quite sure if there's a "best way" to tackle the following design issue.
I have a Tablayout with 2 Tabs in my MainActivity. Each Tab is a different Fragment. I go to Tab1 and see Fragment1. I need to launch a new Fragment (1A) from Fragment 1 and am not sure the best way to do it? I was thinking about one of these.
A) Take the Tabs out of my MainActivity and place them in a separate MainFragment, which gets launched with the app. That way when the user launches Fragment 1A, it replaces just the 1 MainFragment with the Tabs.
or
B) Keep the Tabs in the MainActivity and find a way to replace Fragment 1 with Fragment 1A when under Tab1.
Any suggestions would be appreciated. Thank you.
I think you shouldn't do both of points... Frag1 visible under Tab1 should contain all the layout (including initialy hidden) and logic for this view. If you need to show smth new it may be smaller (then popup, dialog etc.) or expand some layout, maybe with some animation (you may still use ViewPager inside Fragment inside ViewPager, disable touch events and manipulate scrolling programmatically...).
When Action picked by user is intended to show smth so-much-improtant that previous screen is not needed at all then you should probably open new Activity
PS. If you insist to replace current "screen" (in fact Activitys content) note that title of Tab1 may not representing what contains Frag1A. It very depends what kind of content you have there. You may consider move TabLayout/RecyclerView to e.g. FrameLayout container and add to it you Frag1A covering whole previous view including Tabs. In current design guidelines you can even find suggested solution for way of showing new fragment - with circular reveal animation
I do not understand very well what you want, but possibly this.
Use FragmentPagerAdapter..
public class TabsPagerAdapter extends FragmentPagerAdapter {
private static final int NUM_TABS = 3;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return Tab1Fragment.newInstance();
case 1:
return Tab2Fragment.newInstance();
default:
return Tab3Fragment.newInstance();
}
}
#Override
public int getCount() {
return NUM_TABS;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0){
return "Tab 1";
}
if (position == 1){
return "Tab 2";
}
return "Tab 3";
}
In your activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Tabs
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
TabsPagerAdapter adapter = new TabsPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabs.setupWithViewPager(pager);
}
Related
Hell community,
I am new to Android and I could not find a good answer to that problem:
I want to use a bottom-navigation and some of the elements should also use tabs.
Now my question is what is the most common (best) way of implementing that?
I am confused in if I should use activities or Fragments for this navigation.
Is it an okay way just using fragments for both, the bottom-navigation and the tabs or is the best way using activities for the bottom-navigation and only fragments for the tabs?
Best regards
The best approach is to use Fragments for both. If you use an Activity for each screen reachable from the bottom navigation, you will have to put a BottomNavigationView in each and duplicate a lot of code, as well as tweaking transitions between those activities.
Activities should be considered entry-points of your application: when clicking on the app icon in the launcher, the main activity defined in the Manifest is started.
For anything else (portions of the UI, parts of a navigation flow...) you may use Fragments.
Here is a sample Activity and Fragments organization to solve your case:
MainActivity
|--- TopLevelFragment1
|--- TopLevelFragment2
| |--- TabFragment1
| |--- TabFragment2
| |--- TabFragment3
|
|--- TopLevelFragment3
|--- TopLevelFragment4
As you can see in the above schema, an Activity can host child fragments, and fragments can also have nested fragments (also called "child fragments").
TopLevelFragmentN are fragments that are displayed when selecting an item in the BottomNavigationView. TabFragmentN are fragments that are displayed when selecting a Tab from TopLevelFragment2.
Let's dive into the implementation. I have not tested the following pieces of code, those are just provided for guidance.
Here is sample code for the activity:
main_activity.xml
<CoordinatorLayout android:id="#+id/coordinator_layout">
<FrameLayout android:id="#+id/fragment_host"><!-- TopLevelFragments will be displayed here --></FrameLayout>
<BottomNavigationView android:id="#+id/bottom_nav"/>
</CoordinatorLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// Retrieve a reference to the BottomNavigationView and listen for click events.
BottomNavigationView bottomNav = findViewById<BottomNavigationView>(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(item -> {
// Depending on the clicked item, change the displayed TopLevelFragment.
switch(item.getItemId()) {
case R.id.top_level_1:
showTopLevelFragment(new TopLevelFragment1());
return true;
case R.id.top_level_2:
// Do the same with other TopLevelFragments
return true;
default:
return false;
}
}
// Show the first TopLevelFragment by default.
showTopLevelFragment(new TopLevelFragment1());
}
private void showTopLevelFragment(Fragment fragment) {
// Use the fragment manager to dynamically change the fragment displayed in the FrameLayout.
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_host, fragment)
.commit();
}
}
Please refer to the documentation to understand how to define items in the BottomNavigationView.
Now, let's focus on the TopLevelFragment2 that contains tabs. It is a common pattern to use TabLayout with a ViewPager, so that you can move from one tab to another by swiping left or right.
top_level_fragment_2.xml
<ConstraintLayout android:id="#+id/constraint_layout">
<AppBarLayout android:id="#+id/appbar_layout">
<Toolbar android:id="#+id/toolbar"/>
<TabLayout android:id="#+id/tab_layout"/>
</AppBarLayout>
<ViewPager android:id="#+id/tab_pager"/>
</ConstraintLayout>
TopLevelFragment2.java
public class TopLevelFragment2 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.top_level_fragment_2, container, false);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MyTabPagerAdapter tabPager = new MyTabPagerAdapter(getFragmentManager());
ViewPager viewPager = getView().findViewById(R.id.tab_pager);
viewPager.setAdapter(tabPager);
// Display a tab for each Fragment displayed in ViewPager.
TabLayout tabLayout = getView.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
static class MyTabPagerAdapter extends FragmentPagerAdapter {
MyTabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3; // One for each tab, 3 in our example.
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return new TabFragment1();
case 1:
// Return a new instance of the fragment associated with the tab at position 1
default:
throw new IllegalArgumentException();
}
}
}
}
After those steps, all you have to do is to write the code for the other fragments.
Okay i'll try and make this as clear as possible. I have a Fragment called CheckerManager which contains a ViewPager. This ViewPager will allow the user to swipe between 3 Fragments all of which are an instance of another Fragment called CheckerFragment. I'm using a FragmentPagerAdapter to handle paging. Here's how it looks
private class PagerAdapter extends FragmentPagerAdapter {
CharSequence mTabTitles[];
public PagerAdapter(FragmentManager fm, CharSequence tabTitles[]) {
super(fm);
mTabTitles = tabTitles;
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
return CheckerFragment.newInstance(MainFragment.DRAW_TITLE_LOTTO);
case 1:
return CheckerFragment.newInstance(MainFragment.DRAW_TITLE_DAILY);
case 2:
return CheckerFragment.newInstance(MainFragment.DRAW_TITLE_EURO);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return mTabTitles[position];
}
#Override
public int getCount() {
return 3;
}
}
I know that the ViewPager will always create the Fragment either side of the current Fragment. So say my 3 CheckerFragments are called A, B and C and the current Fragment is A. B has already been created. But my problem is that even though I am still looking at Fragment A, Fragment B is the 'active' Fragment. Every input I make is actually corresponding to Fragment B and not A. The active Fragment is always the one which has been created last by the ViewPager.
I've looked at quite a few things to see if anyone has had the same problem but i'm finding it difficult to even describe what's wrong. I think it's something to with the fact that all of the ViewPagers fragments are of the same type ie - CheckerFragment. I have a working implementation of a ViewPager inside a fragment elsewhere in the application and the only difference I can tell is that each page is a different type of Fragment.
Any help would be appreciated!
*EDIT
PagerAdapter adapter = new PagerAdapter(getChildFragmentManager(), tabTitles);
ViewPager viewPager = (ViewPager)view.findViewById(R.id.viewPagerChecker);
viewPager.setAdapter(adapter);
I feel pretty stupid but I found out what the issue was. In my CheckerFragment I would call getArguments() to retrieve a String extra and I would use this to determine how to layout the fragment. Problem was I made this extra a static member of CheckerFragment. So every time a new Fragment was created it was using the most recent extra.
Moral of the story - Don't make your fragments extra a static member if you plan on making multiple instances of that fragment.
I am implementing Pager Adapter in a Fragment. When I load the screen First time, it works fine. If i switch to other fragment and goes to previous fragment again the it shows empty screen. If I swipe between different tap and move to first tab again then it shows data.
I think on moving back the tabs which are visible didn't load data but once they are out of view during swipe navigation it loads data.
Here is my Pager Adapter:
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
case 3:
return new Fragment4();
case 4:
return new Fragment5();
case 5:
return new Fragment6();
}
return null;
}
#Override
public int getCount() {
return 6;
}
}
I am setting my adapter like this:
viewPager = (ViewPager) rootView.findViewById(R.id.my_pager);
mAdapter = new MyPagerAdapter(getActivity().getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Just Check if you are using getFragmentManager() to initialize the adapter , Try using getChildFragmentManager() like this :
mAdapter = new MyPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
Use this,
public class MyPagerAdapter extends android.support.v4.app.FragmentStatePagerAdapter
I was having the same problem and wasted a whole day on this. So I am posting the solution for my issue so that someone else doesn't have to struggle and waste a lot of time.
My problem was that the Fragments inside viewpager were getting invoked(debugger was getting hit) but I was not able to see it in the view(Even for the 1st time).
Issues were:
The parent of the ViewPager was a Fragment.
I had to use getChildFragmentManager() instead of getFragmentManager().
The parent of the Parent Fragment was a NestedScrollView(The activity in which Fragment was populated).
For some reason, even if we keep the height and width of viewpager as matchparent, it was not getting picked up and was defaulted to 0(Even though it was filled in the preview of the xml).
To fix this, we have to add android:fillViewport="true" in your NestedScrollView
Hopefully someone will find this helpfull :)
Because you are not allowed to have nested fragments.
Fragments within Fragments
Change you class to extends FragmentActivity and it should work
My ViewPager is in a Fragment.
I solve this problem by Change FragmentPagerAdapter to FragmentStatePagerAdapter,and also use getFragmentManager().
it's works fine;
use FragmentStatePagerAdapter instead of FragmentPagerAdapter
and add this line after you set the adapter
viewPager.setOffscreenPageLimit(6);\\ add the number of fragments you have
This will remember fragments in memory and it will never show empty screen. But please keep in mind that this will keep each page's data in memory so use it accordingly.
I have ActionBar Tabs setup. It consists of 4 tabs. Everything is fine until I navigate away from TabbedFragment and returning back.
I create tabs like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getActionBar();
tabs = Lists.newArrayList();
tabs.add(new TabDefinition<>("Tab 1"));
tabs.add(new TabDefinition<>("Tab 2"));
tabs.add(new TabDefinition<>("Tab 3"));
tabs.add(new TabDefinition<>("Tab 4"));
for (TabDefinition tab : tabs) {
actionBar.addTab(actionBar.newTab()
.setText(tab.text)
.setTag(tab.tag)
.setTabListener(this));
}
}
And initialize adapter like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.paging_tab_container, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = (ViewPager) view.findViewById(R.id.pager);
viewPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
return tabs.get(position).fragment;
}
#Override
public int getCount() {
return tabs.size();
}
});
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
getActionBar().setSelectedNavigationItem(position);
}
});
viewPager.setCurrentItem(getActionBar().getSelectedNavigationIndex(), true);
}
When returning back to TabbedFragment selected tab and 1 next to it would not have any content. Just empty view. But if I select current + 2 fragment content is loaded. And then returning to that first fragment content is reloaded.
For example I have A, B, C, D tabs. Before leaving TabbedFragment I had selected tab A.
When returning to TabbedFragment I still am at tab A, but it's empty. So is tab B.
But when selecting tab C it is created and loaded. Returning to tab A it is recreated.
What could be the problem here?
After a while ran into the same problem again, so updating this question.
If you're using FragmentStatePagerAdapter you should provide FragmentManager via getChildFragmentManager() instead of getFragmentManager(). See Issue 55068: ViewPager doesn't refresh child fragments when back navigation via backstack
Okay so When using a FragmentStatePagerAdapter your fragments will be destroyed when you navigate anymore than one fragment Away since by default offScreenPageLimit is set to 1 by default just as mentioned above.
Typically this Class is used for an activity that has a very large set of Fragments, i.e have to scroll through a large amount of views. If your application does not need more than say 3-4 tabs I would suggest using FragmentPagerAdapter instead, and then specifying your offScreenPageLimit to something like 3, so if you get to the 4th Tab, all 3 tabs before will still be in memory.
Here is some Sample Code for a project on github that i created illustrating how to dynamically load the fragments if you don't want to add this offScreenPageLimit.
https://github.com/lt-tibs1984/InterfaceDemo/blob/master/src/com/divshark/interfacedemo/InterfaceDemoMain.java
Walk through all this code in this Class, and you will see how I'm dynamically loading the fragments, each time my ViewPager is slid over. Most notably at the bottom.
You can download this code, and use it as a test base for what you want to do.
Try adding the setOffScreenPageLimit(2) in the onCreate() method for the viewPager and notice the different behavior. To check the behavior, edit the text in fragment 1. Navigate Away and navigate back, with this set or not. You will see when it is set, the fragment's text remains what you change it to, since the fragment is never recreated.
Please provide additional questions if you have them.
GoodLuck
UPDATE
private static final String [] fragmentClasses = {"com.example.project.YourFragment1","com.example.project.YourFragment2","com.example.project.YourFragment3"};
viewPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragmentAtPosition = null;
// $$$$ This is the Important Part $$$$$
// Check to make sure that your array is not null, size is greater than 0 , current position is greater than equal to 0, and position is less than length
if((fragmentClasses != null) && (fragmentClasses.length > 0)&&(position >= 0)&& (position < fragmentClasses.length))
{
// Instantiate the Fragment at the current position of the Adapter
fragmentAtPosition = Fragment.instantiate(getBaseContext(), fragmentClasses[position]);
fragmentAtPosition.setRetainInstance(true);
}
return fragmentAtPosition;
}
#Override
public int getCount() {
return fragmentClasses.length;
}
});
The problem exists in the Fragments you use as tabs, I think. They seem to not show anything when they are resumed (see Fragment lifecycle). The "weird" issue that only the currently selected +/-1 tab is empty, is because the offScreenPageLimit of your ViewPager is 1 by default. All tabs above this threshold are re-created.
Therefore, increasing the value will -- in your case -- cause all your tabs to appear empty after resuming. Check in your Fragment code which lifecycle methods you use to inflate your layout, set adapters and so forth, because that's what's causing your trouble.
I guess this happens because while loading fragment android loads current and current+1, if you debug you would not see onPause getting called for the immediate next fragment.
You can reload content programmatically in onTabChanged() method of TabHost.OnTabChangeListener.
After doing much research, this worked for me.
I have a complex layout with 3 tabs in a fragment, that gets switched out for other fragments. I realized that the ViewpagerAdapter will retain state, even if you press the home button. My problem was switching back and forth would null out the child fragment UI view elements and crash. The key is to not new out your ViewPagerAdapter. Adding the null check for the Adapter worked for me. Also, be sure to allocate setOffscreenPageLimit() for your needs. Also, from what I understand setRetainInstance(true); should not be used for fragments that have UI, it is designed for headless fragments.
In the fragment that holds your Tabs:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab, container, false);
tabLayout = (TabLayout) view.findViewById(R.id.tablayout);
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
//Important!!! Do not fire the existing adapter!!
if (viewPagerAdapter == null) {
viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());
viewPagerAdapter.addFragments(new AFragment(), "A");
viewPagerAdapter.addFragments(new BFragment(), "B");
viewPagerAdapter.addFragments(new CFragment(), "C");
}
//Allocate retention buffers for three tabs, mandatory
viewPager.setOffscreenPageLimit(3);
tabLayout.setupWithViewPager(viewPager);
viewPager.setAdapter(viewPagerAdapter);
return view;
}
Or more simply when navigating back to tabbedfragment (assuming you use an intent and the fragment is within an activity) use:
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
This keeps the original activity and moves it to the top of the stack rather than recreating it, thus you never need to recreate the viewPager.
Currently, with a FragmentActivity, I toggle among 2 type of Fragments using the following code.
private void toggle() {
Fragment oldFragment = getSupportFragmentManager().findFragmentById(R.id.content);
Fragment fragment = null;
if (oldFragment instanceof ColorFragment) {
fragment = new ViewPagerFragment();
} else {
fragment = new ColorFragment(android.R.color.black);
}
getSupportFragmentManager().beginTransaction().replace(R.id.content, fragment).commitAllowingStateLoss();
}
2 Fragments are being toggle.
ColorFragment - A simple fragment which fill up its background with solid black color.
ViewPagerFragment - A fragment contains ViewPager. User can swipe between a purple color fragment, and a blue color fragment.
The code which responsible for swiping purple and blue color fragments are as below.
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ColorFragment(android.R.color.holo_purple);
default:
return new ColorFragment(android.R.color.holo_blue_bright);
}
}
}
However, I encounter the weird behavior during toggling.
Black color fragment was shown.
Toggling.
View pager, which can swipe between purple and blue fragments shown.
Toggling.
Black color fragment was shown.
Toggling.
Nothing shown, as MyFragmentPagerAdapter's getItem is not being triggered.
I think my situation is similar to FragmentPagerAdapter getItem is not called
However, I prefer not to use FragmentStatePagerAdapter, because of the cost of potentially more overhead when switching between pages.
Any workaround to overcome this problem?
I include a complete workable source code to demonstrate this problem : https://www.dropbox.com/s/jok9tz5ktvfcteo/viewpagerbug.zip
Any workaround to overcome this problem?
I've downloaded your code and the problem appears because you don't handle those Fragments right. Most precisely you use nested Fragments in the ViewPager based Fragment and for that ViewPager you create the adapter like this:
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(this.getFragmentManager());
Instead, you should be using getChildFragmentManager() to bind the nested fragments:
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(this.getChildFragmentManager());
Also, you shouldn't pass data through a constructor to a Fragment as that data will not survive a configuration change and bad things will start to appear. Use a Bundle instead.
Global working tested solution.
getSupportFragmentManager() keeps the null reference some times and View pager does not create new fragment instance.Since it finds reference to same fragment. So to over come this use getChildFragmentManager() solves problem in simple way.
Don't
new PagerAdapter(getSupportFragmentManager(), fragments);
Do
new PagerAdapter(getChildFragmentManager() , fragments);
Simple use FragmentStatePagerAdapter instead of FragmentPagerAdapter
or
you can use new MyFragmentPagerAdapter(this.getChildFragmentManager())
Hope it will help you :)
In my case I was correctly calling
MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(this.getChildFragmentManager());
but then in the nested fragment I was trying to replace the container fragment with another one by using:
getFragmentManager()
You need to go to the activity and call
getActivity().getSupportFragmentManager();
In my cases it worked after add this to my FragmentPagerAdapter:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
and I also used getChildFragmentManager() like Luksprog said