UserVisibilityHint function is not called every time when fragmnent is viable - android

I have 4 fragments in my viewpager I want to send a call for data every time when my fragment is visible to user. I am using uservisibilityhint() function but it is called only first time in view page and then again it is never called whenever that fragment is visible . is there any way to call it manually every time when the fragment is visible so that I can now that my fragment is visible or not to the user . how can i do this thing

Use
#Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
if (visible && isResumed()) {
// Your code
}
}

Use a Listener on your ViewPager in the Activity like below:
viewPager.setOnPageChangeListener(new OnPageChangeListener...
and here in the listeners callback detect the current View using this method:
ViewPager.getCurrentItem()
and then wire an interface between your activity and four fragments so you can notify which View should try loading fresh data.

Related

Fragment lifecycles in ViewPager

There is a ViewPager with Fragments generated dynamically.
Questions:
What is the way to catch the moment when user slides away from the fragment (so I can bring it into "clean", "init" state)?
or
How to catch moment when a Fragment is scrolled in?
Problems:
Have checked Fragment Lifecycle, but none of them is getting triggered when scrolled out/in (using ViewPager)
Lifecycle phases are triggered only if I scroll 2+ Fragments (those 3rd one is getting Paused/Resumed).
To get a callback when a fragment gets visible to the user you can override the setUserVisibleHint method, like this:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
//Put your 'init' logic here
}
}
the variable isVisibleToUser will give the status of the visibility, so you can use the same method to handle when the fragment goes out.
addOnPageChangeListener
void addOnPageChangeListener (ViewPager.OnPageChangeListener listener)
Add a listener that will be invoked whenever the page changes or is incrementally scrolled. See ViewPager.OnPageChangeListener.
Components that add a listener should take care to remove it when finished. Other components that take ownership of a view may call clearOnPageChangeListeners() to remove all attached listeners.
You can implement this listener to track the movement of the fragments in the ViewPager.
There is also a method setOffscreenPageLimit() which Set the number of pages that should be retained to either side of the current page and it's default value is 1 and minimum value can be set to 0.

ViewPager Current Fragment Visibility

What I Have
I have a ViewPager with 5 fragments. I want to animate some TextViews inside the fragments whenever they become visible to the user.
I can't use onResume() as the fragments to the left and right are already created. I can't use setUserVisibilityHint() as it is called before onCreateView() so the views are not ready yet.
So what should be the way to animate the views whenever a particular fragment becomes visible to the user?
I'm not sure, but if you say that setUserVisibilityHint calls before onCreateView, than check view on null here (make reference on view - field), and if it not null - animate it. Also animate it always in onCreateView.
(1) I can't use onResume() as the fragments to the left and right are already created.
(2) I can't use setUserVisibilityHint() as it is called before onCreateView() so the views are not ready yet.
So what should be the way to animate the views whenever a particular fragment becomes visible to the user?
You're right on (1) and (2). However, setUserVisibilityHint() gets called Once Again with a True value after the Fragment comes to Front on Display. But on First Run the Fragment to be shown gets its setUserVisibilityHint() called before onCreateView().
SOL: You should use the above said behaviour of setUserVisibilityHint() along with onResume() to animate the views whenever a particular fragment becomes visible to the user.
Scenario 1: On First Run: Displayed Fragment's setUserVisibilityHint(boolean isVisibleToUser) gets called with
True param value. But as the Fragment's State is not Resumed we postpone and let the onResume() handle animation.
Scenario 2: For Other Fragments that are already in Resume State, setUserVisibilityHint(boolean isVisibleToUser) will get called with
True param it they come on to Display. Here you check for the
Fragment Animated or not and Do animation.
CODE
a) Declare two Global Boolean Fields: isAnimated and isOnDisplay
a.1) Set isAnimated boolean to True;
b) Override setUserVisibilityHint(boolean isVisibleToUser):
Here you set isOnDisplay boolean to isVisibleToUser and check is the Fragment Not Already Animated and is in Resumed State and is Visible to User.
{ if(!isAnimated && isResumed() && isVisibleToUser) // DO Animation }
c) Override onResume()
Check if the Fragment Not Already Animated and is Visible to User.
{ if(!isAnimated && isVisibleToUser) // DO Animation }
I know this answer might be a bit late, but I hope it can help others in a similar situation.
You could use FragmentViewPager library (I am the author), which deals with the issue you are facing for you. Its features are:
allows its Fragment pages to get notified when they are actually
visible/invisible to the user
supports multiple levels of FragmentViewPagers (nesting)
provides methods to control its paging
A basic usage would be:
Attach FragmentViewPager programmatically or via XML to an Activity
or Fragment, as you would with native ViewPager
Set FragmentViewPager's adapter. Your adapter should inherit
com.sbrukhanda.fragmentviewpager.adapters.FragmentPagerAdapter or
com.sbrukhanda.fragmentviewpager.adapters.FragmentStatePagerAdapter
Override onResumeFragments() of the hosting Activity and call
FragmentViewPager.notifyPagerVisible():
private FragmentViewPager mFragmentsPager;
#Override
public void onResumeFragments() {
super.onResumeFragments();
mFragmentsPager.notifyPagerVisible();
...
}
or onResume() of the hosting Fragment and call
FragmentViewPager.notifyPagerVisible():
private FragmentViewPager mFragmentsPager;
#Override
public void onResume() {
super.onResume();
mFragmentsPager.notifyPagerVisible();
...
}
Override onPause() of the hosting Activity or Fragment and call
FragmentViewPager.notifyPagerInvisible():
private FragmentViewPager mFragmentsPager;
#Override
public void onPause() {
super.onPause();
mFragmentsPager.notifyPagerInvisible();
...
}
Implement FragmentVisibilityListener on all Fragment pages that you
wish to receive callbacks for their visibility state
You are ready to go!
If you wish to see a more complete sample code, then check project's sample project.
If you want to do it in individual fragments, then you can use isVisible()
for each fragment in your fragment transition and create a listener. Whenever a fragment will become visible , listener will be invoked and each fragment will implement that listener and do your intended task in the overridden method.

Restoring a Fragment State when returned after clicking Backpressed of another fragment

Here is my problem area:
I have a Fragment A. Once it is attached, in its onCreateView, I load a webservice to fetch the data from the server and after that I set that data on the list view using a Base Adapter. Now on the Item Clicks of the list view I replace the Fragment A with Fragment B using replace Methods of the Fragment Transactions and addtoBackstack("FragmentA").
FragmentManager fm =getActivity().getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, Fragment B).commit();
Now here when I press back button on Fragment B, it takes me to Fragment A but the webservice again starts loading.
My Problem: I just want that when it returns to Fragment A, it should show its previous state and should not call the webservices again.
Thanks
OnCreateView for a fragment runs on the creation of the view every time it needs to be drawn. By going back you are causing the view to be recreated and hence the webservices are loading again.
I believe that if you only want the web services to load once then you could move the code to the "onCreate" method instead, but its probably a better idea to move this code to "onResume" instead and include some logic that checks whether you need to load your webservices again or not.
This way everytime the fragment is paused and then loaded again you could ensure that the fragment still has everything it needs.
(source: xamarin.com)
EDIT:
So for example you could have
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
if (data == null) { //Or list is empty?
getWebData()
}
}

Android - how to refresh tab contents

I have two tabs with fragments created in my activity, the data of the second tab depends on the first tab data.
Both the tabs are containing list items, when I delete an item from first tab's list, it gets deleted but the second tab still shows the data. I need to go back from activity and load again to see the updated data in second tab.
Is there any way that I can refresh the second tab content whenever I delete/update list item of first tab?
Note: I have tried -
detach()
attach()
and
runQueryOnBackgroundThread()
notifyDataSetChanged()
In onResume nothing seems to be working. Any help would help a lot
You should learn about Interface communication. Read this http://developer.android.com/training/basics/fragments/communicating.html will help you.
you should override setUserVisibleHint method in your fragment and put your refreshing code in it
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
}
}
I got this code in help.Hope it will help more people.Or refer my question here
http://stackoverflow.com/questions/40505019/how-to-refresh-tabs-content-dynamically-while-switching-between-one-tab-to-other/40505242#40505242

ViewPager, when do I save state of my fragment

I have a fragment that loads data in the onResume/onCreate method and saves data in the onPause method. When I place this fragment in a viewpager it is initialized when it is the frament 1 left or 1 right to the current fragment shown on the screen.
During this time onResume is called and the fragment data is loaded. Which is fine.
However when the fragment is visible and the user swipes to another fragment no life cycle methods are called that I can find (onPause/ onStop/ onDetatch .. etc). The onPause/ onStop are only called when the fragment is 2 fragments left or 2 fragments right to the current one shown on the screen.
I would like to know how other people handle this, when do you save state in a Fragment which is shown in a ViewPager?
you can call this method to understand which fragment you are in
#Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if((visible) )
{
//do something here
}
}

Categories

Resources