- Android for professionals
- Monday, 24 June 2013
- Get current visible fragment page in a ViewPager
- 174 comments:
- Android Fragments Common Queries & Common Mistakes
- getSupportFragmentManager and getChildFragmentManager
- Callback from DialogFragment, ChildFragment, BottomSheetFragment to parent fragment
- Fragments when using ViewPager and adapters FragmentStateAdapter and FragmentPagerAdapter which one one to use when
- amodkanthe/ViewPagerTest
- Contribute to amodkanthe/ViewPagerTest development by creating an account on GitHub.
- FragmentTransaction add vs replace
- Fragment receivers, broadcasts and memory leaks
- Fragment BottomBarNavigation and drawer how to handle these
- Android for professionals
- Monday, 24 June 2013
- Get current visible fragment page in a ViewPager
- 174 comments:
Android for professionals
Monday, 24 June 2013
Get current visible fragment page in a ViewPager
There are two ways to get current visible fragment page in ViewPager.
You can set a unique tag on each fragment page like below
etSupportFragmentManager().beginTransaction().add(myFragment, «Some Tag»).commit();
then retrieve the fragment page
You need to keep track of the string tags and link them with the fragments. Use a HashMap to store each tag along with the current page index, which is set at the time when the fragment page is instantiated.
To get current visible page’s tag you need to call
and then to get current visible fragment call
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);
Second approach is also similar to the first one, here also we have to keep track of all the active fragments. In this case, you keep track of the fragments in the FragmentStatePagerAdapter.
You should not keep the reference of inactive fragments, to remove inactive fragments from mPageReferenceMap we need to implement FragmentStatePagerAdapter’s destoryItem(. ) method and do like below.
and to access the current visible fragment page, you then call
MyAdapter’s getFragment(int) method should be like this
174 comments:
Override setPrimaryItem from your FragmentPagerAdapter or FragmentStatePagerAdapter, argument object is your current fragment:
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) <
if (mCurrentFragment != object) <
mCurrentFragment = (Fragment) object;
>
super.setPrimaryItem(container, position, object);
>
Thanks for this solution.
Very good solution! thanks.
That worked. Thanks for the tip
IEEE Final Year Project centers make amazing deep learning final year projects ideas for final year students Final Year Projects for CSE to training and develop their deep learning experience and talents.
IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation.
corporate training companies in india corporate training companies in india
corporate training companies in chennai corporate training companies in chennai
I have read your blog its very attractive and impressive. I like it your blog. Digital Marketing Company in Chennai
That is for to get the which fragment we are in?
I have totally 20 fragments . I need to show 1/20,2/20 like that any one helps me?
Add fragments like this.
public class FragmentsPagerAdapter extends FragmentStatePagerAdapter <
int numberOftabs;
Context context;
FragmentManager fm;
Map fragmentsMap = new HashMap<>();
public FragmentsPagerAdapter(@NonNull FragmentManager fm, int numberOftabs, Context context) <
super(fm);
this.fm = fm;
this.numberOftabs = numberOftabs;
this.context = context;
>
public FragmentsPagerAdapter(@NonNull FragmentManager fm, int behavior, int numberOftabs) <
super(fm, behavior);
this.numberOftabs = numberOftabs;
>
@NonNull
@Override
public Fragment getItem(int position) <
Fragment fragment;
switch (position) <
case 0:
fragment = new FirstFragment(context);
break;
case 1:
fragment = new SecondFragment(context);
break;
case 2:
fragment = new ThirdFragment(context);
break;
default:
throw new IllegalStateException(«fragment is null at » + position);
>
fragmentsMap.put(position, fragment);
return fragment;
>
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) <
super.destroyItem(container, position, object);
fragmentsMap.remove(position);
>
public Fragment getFragment(int position) <
return fragmentsMap.get(position);
>
@Override
public int getCount() <
return numberOftabs;
>
Источник
Android Fragments Common Queries & Common Mistakes
Fragment class in Android is used to build dynamic User Interfaces. Fragment should be used within the Activity. A greatest advantage of fragments is that it simplifies the task of creating UI for multiple screen sizes. A activity can contain any number of fragments.
Now this meaning of fragment sounds good and easy, right? But there is lot more involved, this article covers main needs and common mistakes while using Fragments.
I am assuming you are having basic knowledge of Fragment and Fragment lifecycle callbacks also I am assuming you know how implement communication between two fragments this article goes beyond that
So here are a few obstacles related to fragments some of you must have faced already, some of you might face later.
- FragmentManager: getSupportFragmentManager and getChildFragmentManager. Which one to use when and avoid memory leaks while using them.
- Callback from DialogFragment, ChildFragment, BottomSheetFragment to parent fragment.
- Fragments when using ViewPager and when to use FragmentStateAdapter vs FragmentPagerAdapter.
- When to use FragmentTransaction add vs replace ?
- Fragment receivers, broadcasts and memory leaks.
- Fragment BottomBarNavigation and drawer. How to handle these?
- commit() and commitAllowingStateLoss()
- Fragment option menus.
- Fragment getActivity(), getView() and NullPointers Exceptions.
- onActivityResult with nested fragments.
- Fragment and Bundle.
- Back Navigation.
Whoa . see its a big list, reply in comment if anyone wish to add something more to the list.
getSupportFragmentManager and getChildFragmentManager
FragmentManager is class provided by the framework which is used to create transactions for adding, removing or replacing fragments.
- getSupportFragmentManager is associated with Activity consider it as a FragmentManager for your Activity .
So whenever you are using ViewPager, BottomSheetFragment and DialogFragment in an Activity you will use getSupportFragmentManager
- getChildFragmentManager is associated with fragment.
Whenever you are ViewPager inside Fragment you will use getChildFragmentManager
Here is official link for this for better understanding.
Now coming to common mistakes people do when they are using ViewPager inside a Fragment they pass getSupportFragmentManager which is fragment manager for Activity and it causes issues as such memory leaks, ViewPager not updated properly sometimes etc.
Most important issue caused by using getSupportFragmentManager in Fragment is memory leak, let me tell you how? Your Fragment has stack of fragments which is used by ViewPager or any other thing and all these fragments stack is in activity since you used getSupportFragmentManager , now if close your Parent fragment it will be closed but it will not be destroyed because all child Fragments are in activity and they are still in memory which does not allow to destroy Parent Fragment hence causing leak. It will not just leak parent fragment but also leak all child fragments since none of them can be cleared from heap memory. So never try to use getSupportFragmentManager in a Fragment
Callback from DialogFragment, ChildFragment, BottomSheetFragment to parent fragment
This is very common issue people face when they use BottomSheetFragment or DialogFragment or ChildFragment.
Add a child fragment
Another example bottomSheetFragment
Now suppose you want callback from these child fragments to parent fragments . Most of people create connection between two fragments using activity, few people pass interface listeners as a parameter to fragment which really a bad practice and one should avoid this. Best way calling getParentFragment() from your child fragment to create a call back this is very simple way consider example below.
then setting callback to parent fragment add following code in child fragment.
thats it you can give a callback to your parent fragment now easily.
Using same way you can create a callback from child fragment inside ViewPager to parent fragment who is holding ViewPager.
Fragments when using ViewPager and adapters FragmentStateAdapter and FragmentPagerAdapter which one one to use when
FragmentPagerAdapter stores the whole fragment in memory, and could increase a memory overhead if a large amount of fragments are used in ViewPager . FragmentStatePagerAdapter only stores the savedInstanceState of fragments, and destroys all the fragments when they lose focus.
So when your is going to have many Fragments use FragmentStateAdapter if ViewPager is going to have less than three fragments use FragmentPagerAdapter.
Commonly faced issues
Update ViewPager not working:
People always come across the issue remember ViewPager fragments are managed by FragmentManager either from Fragment or Activity and this FragmentManager holds instance of all ViewPager Fragments.
So when people say ViewPager is not refreshed it’s nothing but old instances of fragments are still being hold by FragmentManager. So you need to find out why FragmentManger is holding instance of Fragments is there any leak or not ideally to refresh ViewPager following code works if it is not you are doing something wrong
Access current Fragment from ViewPager:
This is also very common issue we come across. For this people either create array list of fragments inside adapter or try to access fragment using some tags according to me both methods are not reliable. FragmentStateAdapter and FragmentPagerAdapter both provides method setPrimaryItem this can be used to set current fragment as below.
I am leaving a Github link below to this simple ViewPager project so that everyone can understand better.
amodkanthe/ViewPagerTest
Contribute to amodkanthe/ViewPagerTest development by creating an account on GitHub.
FragmentTransaction add vs replace
In our Activity we have a container and inside this container we display our Fragments
add will simply add fragment to container suppose you add FragmentA and FragmentB to container. Container will have FragmentA and FragmentB both and suppose if container is FrameLayout fragments are added one above the other. replace will simply replace a fragment on top of container so if I call create FragmentC now and call replace FragmentB which was on top will removed from container unless you are not calling addToBackStack and now FragmentC will be on top.
So which one to use when. replace removes the existing fragment and adds a new fragment . This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked. Whereas add retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in ‘paused’ state hence when a back button is pressed onCreateView is not called for the existing fragment(the fragment which was there before new fragment was added). In terms of fragment’s life cycle events onPause, onResume, onCreateView and other life cycle events will be invoked in case of replace but they wont be invoked in case of add .
Use replace fragment if don’t need to revisit current fragment and current fragment is not require anymore. Also if your app has memory constraints use replace instead of add.
Fragment receivers, broadcasts and memory leaks
Mistakes people commonly do when using receivers inside a fragment forgot to unregister receiver in onPause or OnDestroy. If you are registering fragment to listen to receiver inside onCreate or OnResume you will have to unregister it inside onPause or onDestroy otherwise it will cause memory leak
Also if have multiple fragments listening to same broadcast receiver make sure you register in onResume and unregister in onPause. Because if you use onCreate and onDestroy for register and unregister other fragments will not receive the broadcast as this fragment is not destroyed
Fragment BottomBarNavigation and drawer how to handle these
When we are using BottomBarNavigation and NavigationDrawer people face issues like fragments recreated, same fragment is added multiple times etc.
So in such case you can use fragment transaction show and hide instead of add or replace.
There is also one beautiful library which take care of navigations and avoid recreation of fragments called FragNav below is link to it
Источник
Android for professionals
Monday, 24 June 2013
Get current visible fragment page in a ViewPager
There are two ways to get current visible fragment page in ViewPager.
You can set a unique tag on each fragment page like below
etSupportFragmentManager().beginTransaction().add(myFragment, «Some Tag»).commit();
then retrieve the fragment page
You need to keep track of the string tags and link them with the fragments. Use a HashMap to store each tag along with the current page index, which is set at the time when the fragment page is instantiated.
To get current visible page’s tag you need to call
and then to get current visible fragment call
Fragment myFragment = getSupportFragmentManager().findFragmentByTag(tag);
Second approach is also similar to the first one, here also we have to keep track of all the active fragments. In this case, you keep track of the fragments in the FragmentStatePagerAdapter.
You should not keep the reference of inactive fragments, to remove inactive fragments from mPageReferenceMap we need to implement FragmentStatePagerAdapter’s destoryItem(. ) method and do like below.
and to access the current visible fragment page, you then call
MyAdapter’s getFragment(int) method should be like this
174 comments:
Override setPrimaryItem from your FragmentPagerAdapter or FragmentStatePagerAdapter, argument object is your current fragment:
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) <
if (mCurrentFragment != object) <
mCurrentFragment = (Fragment) object;
>
super.setPrimaryItem(container, position, object);
>
Thanks for this solution.
Very good solution! thanks.
That worked. Thanks for the tip
IEEE Final Year Project centers make amazing deep learning final year projects ideas for final year students Final Year Projects for CSE to training and develop their deep learning experience and talents.
IEEE Final Year projects Project Centers in India are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation.
corporate training companies in india corporate training companies in india
corporate training companies in chennai corporate training companies in chennai
I have read your blog its very attractive and impressive. I like it your blog. Digital Marketing Company in Chennai
That is for to get the which fragment we are in?
I have totally 20 fragments . I need to show 1/20,2/20 like that any one helps me?
Add fragments like this.
public class FragmentsPagerAdapter extends FragmentStatePagerAdapter <
int numberOftabs;
Context context;
FragmentManager fm;
Map fragmentsMap = new HashMap<>();
public FragmentsPagerAdapter(@NonNull FragmentManager fm, int numberOftabs, Context context) <
super(fm);
this.fm = fm;
this.numberOftabs = numberOftabs;
this.context = context;
>
public FragmentsPagerAdapter(@NonNull FragmentManager fm, int behavior, int numberOftabs) <
super(fm, behavior);
this.numberOftabs = numberOftabs;
>
@NonNull
@Override
public Fragment getItem(int position) <
Fragment fragment;
switch (position) <
case 0:
fragment = new FirstFragment(context);
break;
case 1:
fragment = new SecondFragment(context);
break;
case 2:
fragment = new ThirdFragment(context);
break;
default:
throw new IllegalStateException(«fragment is null at » + position);
>
fragmentsMap.put(position, fragment);
return fragment;
>
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) <
super.destroyItem(container, position, object);
fragmentsMap.remove(position);
>
public Fragment getFragment(int position) <
return fragmentsMap.get(position);
>
@Override
public int getCount() <
return numberOftabs;
>
Источник