ViewPager's first two pages are disappearing, getItem() not called - android

Context:
I'm making a music player and I'm currently working on the miniplayer. The miniplayer lives in a ViewPager along with a floating action button (FAB) for shuffle. Initially, only the FAB is seen on screen. When you click on the FAB, music playback starts, the Fab-Miniplayer ViewPager's page count goes from 1 to 2, and its page is set to the second page, where the miniplayer is. The miniplayer itself in the second page is a vertical viewpager, so one can swipe through to different songs. The miniplayer/vertical viewpager is backed by a PagerAdapter that gets songs from a SongQueue obejct.
The Problem:
If I click on the FAB once, the miniplayer opens and everything works. Then I dismiss the miniplayer to stop playback by swiping back to the FAB page in the ViewPager. After clicking on the FAB to start playback and open the miniplayer for the second time, the first two fragments are never created. The miniplayer vertical ViewPager's PagerAdapter's getItem() methods are never called for item 0 and item 1. On a higher level, the first two songs in the miniplayer aren't showing up. Upon further investigation, the onCreate() methods are being called for the first two songs from the last time the miniplayer was opened, so I'm guessing the ViewPager is implementing some kind of caching or a reference is being held onto for too long because the miniplayer vertical viewpager thinks that it already has the first two songs the second time it is instantiated. Hopefully this problem description makes sense. If there are any questions, I'd be happy to try and go into more detail.
The Code
SongsFragment
/**
* Fragment used to display all of the songs on the device.
*/
public class SongsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "SongsFragment";
private SwipeListView mSwipeListView;
private ViewPager fabMiniPlayerViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
// Initialize the loader to load the list of songs
getLoaderManager().initLoader(SongCursorLoader.ALL_SONGS_ID, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_view_songs, parent, false);
if (view != null) {
mSwipeListView = (SwipeListView) view.findViewById(R.id.list_view_songs);
}
LinearLayout emptyView = (LinearLayout) inflater.inflate(R.layout.list_view_songs_empty, parent, false);
mSwipeListView.setEmptyView(emptyView);
fabMiniPlayerViewPager = (ViewPager) view.findViewById(R.id.fab_miniplayer_ViewPager);
Integer viewPagerPageCount = new Integer(1);
fabMiniPlayerViewPager.setTag(viewPagerPageCount); // The fabMiniPlayerViewPager gets it's page count from the tag so it can be dynamically modified
fabMiniPlayerViewPager.setAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int i) {
if (i == 0) {
// ShuffleFabFragment just houses a single button, the code is below
ShuffleFabFragment fragment = new ShuffleFabFragment();
fragment.setViewPager(fabMiniPlayerViewPager);
return fragment;
}
MiniPlayerFragment fragment = new MiniPlayerFragment();
return fragment;
}
#Override
public int getCount() {
Integer count = (Integer) fabMiniPlayerViewPager.getTag();
return count.intValue();
}
});
fabMiniPlayerViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
// Pass touch events to the list view behind it
mSwipeListView.onTouchEvent(motionEvent);
return false;
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
if (!MusicPlayerService.isStopped()) {
Integer viewPagerPageCount = 2;
fabMiniPlayerViewPager.setTag(viewPagerPageCount);
PagerAdapter adapter = fabMiniPlayerViewPager.getAdapter();
fabMiniPlayerViewPager.setAdapter(adapter);
fabMiniPlayerViewPager.setCurrentItem(1, false);
} else {
Integer viewPagerPageCount = 1;
fabMiniPlayerViewPager.setTag(viewPagerPageCount);
fabMiniPlayerViewPager.getAdapter().notifyDataSetChanged();
}
}
}
ShuffleFabFragment
/**
* Fragment representing the Shuffle Floating Action Button. On FAB click, it turns on shuffle and
* plays a random song. Depending on the user preference, the mini-player will appear or the
* Now Playing view will appear. The ShuffleFabFragment holds a reference to its containing
* ViewPager so it can do the following:
* <p/>
* 1. Add the MiniPlayer fragment to the ViewPager to enable swiping & animations
* 2. Remove the MiniPlayer fragment when it is swiped away
* <p/>
* Once the MiniPlayer is swiped away (to the right), it stops music playback.
*/
public class ShuffleFabFragment extends Fragment {
private static final String TAG = "ShuffleFabFragment";
private ViewPager fabMiniPlayerViewPager;
public void setViewPager(ViewPager viewPager) {
fabMiniPlayerViewPager = viewPager;
fabMiniPlayerViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
if (i == 0) { // MiniPlayer swiped away
Integer viewPagerPageCount = new Integer(1);
fabMiniPlayerViewPager.setTag(viewPagerPageCount);
PagerAdapter adapter = fabMiniPlayerViewPager.getAdapter();
Intent stopMusicIntent = new Intent(getActivity(), MusicPlayerService.class);
stopMusicIntent.setAction(MusicPlayerService.ACTION_STOP);
getActivity().startService(stopMusicIntent);
fabMiniPlayerViewPager.setAdapter(adapter);
}
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shuffle_fab, viewGroup, false);
ImageView shuffleFabImageView = (ImageView) view.findViewById(R.id.shuffle_fab_ImageView);
shuffleFabImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
// Scale up on touch to make the button appear to come closer
view.setScaleX(8f / 7f);
view.setScaleY(8f / 7f);
break;
case MotionEvent.ACTION_UP:
view.setScaleX(1f);
view.setScaleY(1f);
break;
default:
view.setScaleX(1f);
view.setScaleY(1f);
}
return false;
}
});
shuffleFabImageView.setClickable(true);
shuffleFabImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String shuffleMode = PreferencesHelper.getShuffleMode(getActivity());
if (shuffleMode.equals(PreferencesHelper.SHUFFLE_MODE_OFF)) {
PreferencesHelper.setShuffleMode(getActivity(), PreferencesHelper.SHUFFLE_MODE_SMART);
}
SongQueue.initializeQueue(null, true, Song.COLLECTION_TYPE_ALL_SONGS, getActivity().getApplicationContext(), null);
Song firstSong = SongQueue.getSong(0);
firstSong.play(getActivity(), false);
// On Click, update the page count, then set page to miniplayer
Integer viewPagerPageCount = new Integer(2);
fabMiniPlayerViewPager.setTag(viewPagerPageCount);
fabMiniPlayerViewPager.getAdapter().notifyDataSetChanged();
fabMiniPlayerViewPager.setCurrentItem(1, true);
}
});
return view;
}
}
MiniPlayerFragment
/**
* Hosts MiniplayerCardFragments and allows for song skipping
*/
public class MiniPlayerFragment extends Fragment implements ViewPager.OnPageChangeListener {
VerticalViewPager miniplayerCardViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_pager_miniplayer, viewGroup, false);
miniplayerCardViewPager = (VerticalViewPager) view.findViewById(R.id.miniplayer_cards_ViewPager);
miniplayerCardViewPager.setAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
Song song = SongQueue.getSong(position);
return MiniPlayerCardFragment.newInstance(song);
}
#Override
public int getCount() {
return SongQueue.getTotalSize();
}
});
miniplayerCardViewPager.setOnPageChangeListener(this);
SongQueue.addOnQueueChangeListener(new SongQueue.OnQueueChangeListener() {
#Override
public void onNextSongChanged() {
onQueueChanged();
}
#Override
public void onQueueChanged() {
// Force re-layout to update fragments
int queuePosition = SongQueue.getQueuePositionCurrentSong();
PagerAdapter adapter = miniplayerCardViewPager.getAdapter();
miniplayerCardViewPager.setAdapter(adapter);
miniplayerCardViewPager.setCurrentItem(queuePosition, true);
}
#Override
public void onCurrentSongChanged() {
onQueueChanged();
}
});
return view;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
int queuePosition = SongQueue.getQueuePositionCurrentSong();
if (queuePosition < position) {
Intent nextIntent = new Intent(getActivity(), MusicPlayerService.class);
nextIntent.setAction(MusicPlayerService.ACTION_NEXT);
getActivity().startService(nextIntent);
} else if (queuePosition > position) {
Intent prevIntent = new Intent(getActivity(), MusicPlayerService.class);
prevIntent.setAction(MusicPlayerService.ACTION_PREV);
getActivity().startService(prevIntent);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onResume() {
super.onResume();
// Force re-layout to update fragments
int queuePosition = SongQueue.getQueuePositionCurrentSong();
PagerAdapter adapter = miniplayerCardViewPager.getAdapter();
miniplayerCardViewPager.setAdapter(adapter);
miniplayerCardViewPager.setCurrentItem(queuePosition, true);
SongQueue.setPagerAdapter(adapter);
}
}
Screenshots to help visualization

After clicking on the FAB to start playback and open the miniplayer for the second time, the first two fragments are never created. The miniplayer vertical ViewPager's PagerAdapter's getItem() methods are never called for item 0 and item 1.
That is because the standard ViewPager already has pages 0 and 1. To clarify Sanket's answer, setOffscreenPageLimit() indicates how many pages to either side of the current page to create (via getItem()) and cache, and the minimum value is 1. Calls to setOffscreenPageLimit(0) will be ignored.
getItem() is not a means of finding out when the user switches pages. A PageChangeListener is your means of finding out when the user switches pages.
the miniplayer vertical viewpager thinks that it already has the first two songs the second time it is instantiated
It's not being instantiated a second time AFAICT.

ViewPager has bydefault offScreenPagerLimit value 3.. so it may be not loading your first 2 item second time..
try with this
mViewPager.setOffscreenPageLimit(0);
more info

Related

Why the middle tab of viewPager never call onCreateView for itself?

For the 2 last days I spent all my time to try to find a solution to a strange problem in a viewpager with fragment. All fragment contains a listview (which has his own adapter).
Here is the situation :
I have an activity which instantiate a viewpager and an adapter for it and contains the object adapter class.
public class SellerActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.vpContainer2);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs2);
tabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
mViewPager.setCurrentItem(position);
mSectionsPagerAdapter.getItem(position);
Toast.makeText(SellerActivity.this,
"Selected page position: " + position, Toast.LENGTH_SHORT).show();
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_shop, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
Intent i = new Intent(SellerActivity.this, MainActivity.class);
if (id == R.id.action_home) {
startActivity(i);
finish();
return true;
}
if (id == R.id.action_logout) {
mAuth.signOut();
startActivity(i);
finish();
return false;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return SellerFragment.newInstance(position + 1, "1");
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "En Attente";
case 1:
return "En cours";
case 2:
return "Terminées";
}
return null;
}
}
I have then a fragment which looks like this :
public class SellerFragment extends Fragment {
private String title;
private int page;
private AllOrders allOrders;
final List<CommandItemForSeller> orders = new ArrayList<>();
final LinkedHashMap<String, Order> saveOrders = new LinkedHashMap<>();
public SellerFragment(){
}
// newInstance constructor for creating fragment with arguments
public static SellerFragment newInstance(int page, String title) {
SellerFragment fragmentFirst = new SellerFragment();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
allOrders = new AllOrders();
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_seller, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("orders");
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot orders : dataSnapshot.getChildren()) {
String orderString = orders.getValue(String.class);
//allOrders.addOrder(new Order(orderString, orders.getKey().substring(orders.getKey().length() - 4, orders.getKey().length())));
saveOrders.put(orders.getKey(), new Order(orderString, orders.getKey().substring(orders.getKey().length() - 4, orders.getKey().length())));
}
}
#Override
public void onChildChanged (DataSnapshot dataSnapshot, String s){
}
#Override
public void onChildRemoved (DataSnapshot dataSnapshot){
}
#Override
public void onChildMoved (DataSnapshot dataSnapshot, String s){
}
#Override
public void onCancelled (DatabaseError databaseError){
}
};
myRef.addChildEventListener(childEventListener);
orders.clear();
allOrders.clear();
allOrders.addAllOrders(saveOrders.values());
List<Order> selectedOrders = allOrders.getItemsOrderedByStatus(page);
for (int i = 0; i < selectedOrders.size(); i++) {
orders.add(new CommandItemForSeller(selectedOrders.get(i)));
}
CommandItemForSellerAdapter aa = new CommandItemForSellerAdapter(getActivity(), R.layout.pending_listview_item, orders);
ListView lv = (ListView) view.findViewById(R.id.commandListView);
lv.setAdapter(aa);
return view;
}
As you can see each fragment calls content from Firebase Database so it remains asynchronous.
My problem is :
When I try to load "synchronous" data (that I previsouly write in my code), list content is set by onCreate method at the first creation so each fragment for each tab get some content. However, the second tab never ever refresh for new data.
So in a case of asynchronous, onCreate method doesn't return any data (due to the load time) and new datas should be added by the onCreateView (like a refresh) but for the second tab it never happens !
After many hours of debugging, I've just found out the following :
When I switch from tab 1 to tab 2, fragment is rendered for tab 3. When I switch from tab 3 to tab 2, fragment is rendered for tab 1. Even if the getItem(position) returns the right position for the tab, tab 2 now never calls onCreateView method and remains empty.
Please.. tell me why this projet behaves like that, I don't want to give up but I really don't understand what is the issue here.
If you need more specific information, tell me I can give you anything you want.
When using FragmentPagerAdapter, ViewPager keeps adjacent pages "alive" (one to the left and one to the right) - meaning that when you have three fragments only, the second one will be never destroyed. You have to find a different way if you want to refresh data when fragments come into view - one idea is to add listener for page changes, using ViewPager.addOnPageChangeListener method - https://developer.android.com/reference/android/support/v4/view/ViewPager.html#addOnPageChangeListener(android.support.v4.view.ViewPager.OnPageChangeListener)
Then, you can trigger refresh from within onPageSelected callback.
In your case, I think the simplest solution is to make SectionsPagerAdapter implement ViewPager.OnPageChangeListener, store reference to each created Fragment (preferably WeakReference), and then call some refresh method on an appropriate SellerFragment instance.

How to make ViewPager destroy items right after I've scrolled to next page

If we have 4 pages in a View pager and swipe from positions 0 do 3
Item at position 0 is destroyed when we get to position 2, item at position 1 is destroyed when we get to position 4.
I need them to be destroyed right away, because I want the view to be recreated if I go back to it, which doesnt happen at the moment.
public class ViewPagerTutorialAdapter extends FragmentStatePagerAdapter {
public ViewPagerTutorialAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt("page", position);
TutorialPageFragment fragment = new TutorialPageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 4;
}
}
public class TutorialPageFragment extends android.support.v4.app.Fragment {
private ImageView ivTutorialPage;
private TransitionDrawable myTransitionDrawable;
private View rootView;
public TutorialPageFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_tutorial_page, container, false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
ivTutorialPage = (ImageView) rootView.findViewById(R.id.ivTutorialPage);
ivTutorialPage.setImageResource(R.drawable.fadein);
myTransitionDrawable = (TransitionDrawable) ivTutorialPage.getDrawable();
new Timer().schedule(new TimerTask() {
#Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
myTransitionDrawable.startTransition(1000);
}
});
}
}, 1000);
}
}
While this is not exactly answer to asked question, a better practice is not recreate Views if not necessary because it can be expensive to do on more complicated layouts + cause stuttering / extra lag which makes user experience worse.
In this case (running animations when fragment becomes visible) it's better to override setUserVisibleHint in fragment with code to run animation which will trigger when user visits the screen. The main advantage is of course no need to recreate Views and allows Android to perform it's internal optimization naturally.
Try viewPager.setOffscreenPageLimit(1);. This should save only one page near selected one. There is not way to only load selected item at a time according to this.

WebView with FragmentStatePagerAdapter goes blank on calling setCurrentItem

I am working on Swipe Views with Tabs. The code provided in the "EffectiveNavigation" project at the Creating Swipe Views with Tabs page provides a solid starting ground. Experimenting further I added an OnClickListener to the given TextView and added a setCurrentItem to the onClick method. This behaves as expected and the ViewPager jumps to the requested page.
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
((TextView) rootView.findViewById(android.R.id.text1)).setText(
Integer.toString(args.getInt(ARG_OBJECT)));
((TextView) rootView.findViewById(android.R.id.text1)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/*
*setCurrentPagerItem(5); -> omitted here to reduce complexity
*/
mViewPager.setCurrentItem(5);
}
});
return rootView;
}
}
As the project I'm working on requires the loading of static webpages instead of text. I replaced the TextView with a WebView to load a different webpage at every swipe. This works perfectly well. Click events from the HTML side are handled by a JavascriptInterface I have implemented.
It is here that I'm facing a problem. The setCurrentPagerItem method works perfectly well when called outside of the JavascriptInterface. When called from within the JavascriptInterface the WebView shows a blank screen and stays so until a swipe to the right or left is made. A swipe to the right displays the next page to the one requested and a swipe to the left displays the requested page. LogCat shows no errors and this behaviour is consistent across a 4.3 based emulator and a Nexus 7 running 4.4.4. I shall provide the entire code below.
public class CollectionDemoActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide fragments representing
* each object in a collection. We use a {#link android.support.v4.app.FragmentStatePagerAdapter}
* derivative, which will destroy and re-create fragments as needed, saving and restoring their
* state in the process. This is important to conserve memory and is a best practice when
* allowing navigation between objects in a potentially large collection.
*/
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
/**
* The {#link android.support.v4.view.ViewPager} that will display the object collection.
*/
ViewPager mViewPager;
private static Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collection_demo);
context = this;
// Create an adapter that when requested, will return a fragment representing an object in
// the collection.
//
// ViewPager and its adapters use support library fragments, so we must use
// getSupportFragmentManager.
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home button should show an "Up" caret, indicating that touching the
// button will take the user one step up in the application's hierarchy.
actionBar.setDisplayHomeAsUpEnabled(true);
final OnPageChangeListener mPageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int pos) {
final Toast pageNo;
pageNo = Toast.makeText(context,"PAGE "+(Integer.toString(pos+1))+"/100",Toast.LENGTH_SHORT);
pageNo.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
pageNo.cancel();
}
}, 100);
}
};
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
mViewPager.setOnPageChangeListener(mPageChangeListener);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This is called when the Home (Up) button is pressed in the action bar.
// Create a simple intent that starts the hierarchical parent activity and
// use NavUtils in the Support Package to ensure proper handling of Up.
Intent upIntent = new Intent(this, MainActivity.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
// This activity is not part of the application's task, so create a new task
// with a synthesized back stack.
TaskStackBuilder.from(this)
// If there are ancestor activities, they should be added here.
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
// This activity is part of the application's task, so simply
// navigate up to the hierarchical parent activity.
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void setCurrentPagerItem(int item) {
mViewPager.setCurrentItem(item);
}
/**
* A {#link android.support.v4.app.FragmentStatePagerAdapter} that returns a fragment
* representing an object in the collection.
*/
public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new DemoObjectFragment();
Bundle args = new Bundle();
args.putInt(DemoObjectFragment.ARG_OBJECT, i + 1); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// For this contrived example, we have a 100-object collection.
return 100;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
/**
* A dummy fragment representing a section of the app, but that simply displays dummy text.
*/
public static class DemoObjectFragment extends Fragment {
public static final String ARG_OBJECT = "object";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
Bundle args = getArguments();
final WebView webView = (WebView) rootView.findViewById(R.id.webView);
switch(args.getInt(ARG_OBJECT)) {
case 1 :
webView.loadUrl("file:///android_asset/html/index.html");
break;
default :
webView.loadUrl("file:///android_asset/html/page_"+(Integer.toString(args.getInt(ARG_OBJECT)-1))+".html");
break;
}
WebSettings ws = webView.getSettings();
ws.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Object()
{
#JavascriptInterface
public void toPage(String pageNo) {
((CollectionDemoActivity) getActivity()).setCurrentPagerItem(4);
}
}, "external");
return rootView;
}
}
}
I could be wrong but it sounds like you are not updating on the UIThread.
You could try something like this.
getActivity().runOnUiThread(new Runnable(){
#Override
public void run() {
((CollectionDemoActivity) getActivity()).setCurrentPagerItem(4);
}
});

ViewPager.setOffscreenPageLimit(0) doesn't work as expected

The fragments I use in my ViewPager instance are quite resource intensive, so I'd only like to load one at a time. When I try the following:
mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(mPagerAdapter);
My FragmentStatePagerAdapter.getItem(int position) override function is called 3 times, which is what happens when I call mViewPager.setOffscreenPageLimit(1). I would expect it to only be called once, because I specified 0 offscreen pages.
I believe I'm calling everything correctly, because if I call mViewPager.setOffscreenPageLimit(2), FragmentStatePagerAdapter.getItem(int position) is called 5 times as I would expect.
Does ViewPager require a minimum of 1 offscreen pages, or am I doing something wrong here?
The best way that I found was setUserVisibleHint
add this to your fragment
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
// fragment is no longer visible
}
}
Does ViewPager require a minimum of 1 offscreen pages
Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:
Requested offscreen page limit 0 too small; defaulting to 1
You can try like this :
public abstract class LazyFragment extends Fragment {
protected boolean isVisible;
/**
* 在这里实现Fragment数据的缓加载.
* #param isVisibleToUser
*/
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(getUserVisibleHint()) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
protected void onVisible(){
lazyLoad();
}
protected abstract void lazyLoad();
protected void onInvisible(){}
protected abstract void lazyLoad();
protected void onInvisible(){}
First Add
boolean isFragmentLoaded = false;
than
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded) {
//Load Your Data Here like.... new GetContacts().execute();
isFragmentLoaded = true;
}
else{
}
}
this may be old thread but this seems to work for me. Override this function :
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if ( menuVisible ) {
/**
* Load your stuffs here.
*/
} else {
/**
* Fragment not currently Visible.
*/
}
}
happy codings...
ViewPager is default to load the next page(Fragment) which you can't change by setOffscreenPageLimit(0). But you can do something to hack.
You can implement onPageSelected function in Activity containing the ViewPager. In the next Fragment(which you don't want to load), you write a function let's say showViewContent() where you put in all resource consuming init code and do nothing before onResume() method. Then call showViewContent() function inside onPageSelected. Hope this will help.
in my case i wanted to start some animations in views, but with setUserVisibleHint got some issues ...
my solution is :
1/ addOnPageChangeListener for your adapter :
mViewPager.addOnPageChangeListener(this);
2/ implement OnPageChangeListener :
public class PagesFragment extends Fragment implements ViewPager.OnPageChangeListener
3/ override the 3 methodes :
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
}
#Override
public void onPageScrollStateChanged(int state)
{
}
4/ declare and initialize this variable on your class
private static int mTabState = 1;
notice : i have three fragments in my adapter, and use mTabState for setCurrentItem and current position of adapter which recognize which fragment is show to user in time ...
5/ in onPageSelected method add this codes :
if (mTabState == 0 || position == 0)
{
Intent intent = new Intent("animation");
intent.putExtra("current_position", position);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
}
if previous page or current page is page 0(fragment in position 0) then do this stuff
6/ now in your fragment class (fragment in position 0 of adapter), you must create broadcast receiver and register it in onResume method and unregister it onPause methos :
BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if (Objects.equals(intent.getAction(), "animation"))
{
int currentPosition = intent.getIntExtra("current_position", 0);
if (currentPosition == 0)
{
startAnimation();
setViewsVisible();
} else
{
setViewsInvisible();
}
}
}
};
#Override
public void onResume()
{
super.onResume();
LocalBroadcastManager.getInstance(mContext).registerReceiver(broadcastReceiver, new IntentFilter("animation"));
}
#Override
public void onPause()
{
super.onPause();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(broadcastReceiver);
}
summary : i have Fragment Pager Adapter witch shows Three Fragments in it, I want show some Animations on Views in Fragment in Position 0 of Adapter, For this I use BroadcastReceiver. When Fragment is Picked I start the Animation method and shows the Views to User, When Fragment is not Showing to User I try to Invisible Views...
View Pager With only one Page :
This is February 2021: I have able to add only one page with viewPager. The approach is with ViewPager, FragmentPagerAdapter, Tablayout, and a fragment. In my case, I can populate many Pages with many tabs, or only one Page with one Tab. When one tab and one page, on swipe left or right, I can manage to change the chapter of my document (which I want to show next). And when many pages and many tabs, I can change the entire book of documents.
In main Activity Oncreate: (Here is my working code approach, I have changed nothing here from my working code):
if(getIntent()!=null){
if(getIntent().getStringExtra("ONLY_TAFHEEM")!=null)
sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(), suraName, suraId, ayatId, true);
else
sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(), suraName, suraId, ayatId, false);
}else {
sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(), suraName, suraId, ayatId, false);
}
final ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
tabsLayout = findViewById(R.id.tabs);
tabsLayout.animate();
tabsLayout.setupWithViewPager(viewPager);
In Adapter :
#NonNull
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.sendData(mContext, postion, suraName, suraId, ayahId, ARABIC_AYAH, BENGALI_AYAH, actualDbNames[position], tafsirDisplayNames[position]);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tafsirDisplayNames[position];
}
#Override
public int getCount() {
// this is the tricky part // Show pages according to array length. // this may only one // this is the tricky part :
return tafsirDisplayNames.length;
}
And at last the fragments public constructor :
public static PlaceholderFragment sendData(Context mContext, int tabIndex, String suraName, String suraId, String ayahNumber, String arabicAyah, String bengaliAyah, String actualDbName, String displayDbName) {
Log.i("PlaceHolder", "Tafhim sendData: " + bengaliAyah);
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
mContext_ = mContext;
BENGALI_AYAH = bengaliAyah;
_DISPLAY_DB_NAME = displayDbName;
bundle.putInt(ARG_SECTION_NUMBER, tabIndex);
bundle.putString(SURA_NAME, suraName);
bundle.putString(SURA_ID, suraId);
bundle.putString(AYAH_NUMBER, ayahNumber);
bundle.putString(ARABIC_AYAH, arabicAyah);
bundle.putString(ACTUAL_DB_NAME, actualDbName);
bundle.putString(DISPLAY_DB_NAME, displayDbName);
fragment.setArguments(bundle);
return fragment;
}
That's all, just passing the array (of Tab Labels) to the adapter, (it may only one element, in case, for one page), with my need, I can populate one page or more page, and according to this it populate one tab or many tabs : in the above code the array is: tafsirDisplayNames. I can also create the array manually in adapter, when the adapter first called, Or, recreate the array with +-elements, on recreate the MainActivity.
Please Try This Code for resolve issue of refreshing view in Viewpager....
/* DO NOT FORGET! The ViewPager requires at least “1” minimum OffscreenPageLimit */
int limit = (mAdapter.getCount() > 1 ? mAdapter.getCount() - 1 : 1);
mViewPager.setOffscreenPageLimit(limit);
for the "instantiateItem" function, just prepare the fragment, but don't load the heavy content.
Use "onPageChangeListener" , so that each time you go to a specific page, you load its heavy content and show it.
I kind of have the same problem. I found some useful code on this site and transform it.
The min int for mViewPager.setOffscreenPageLimit(...); is 1, so even if you change it to 0 you will still have 2 pages loaded.
First thing to do is to create a static int we will call maxPageCount and override FragmentStatePagerAdapter method getCount() to return maxPageCount:
#Override
public int getCount() {
return maxPageCount;
}
Create then a static method accessible from any where in the program that will allow you to change this maxCount:
public static void addPage(){
maxPageCount++; //or maxPageCount = fragmentPosition+2
mFragmentStatePagerAdapter.notifyDataSetChanged(); //notifyDataSetChanged is important here.
}
Now initialize maxPageCount to 1. When ever you want you can add another page.
In my case when I needed the user to treat the current page first before generated the other. He do it and then, without problem can swipe to the next page.
Hope it help someone.
Use This
// create boolean for fetching data
private boolean isViewShown = false;
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
fetchData();
} else {
isViewShown = false;
}
}
// step 1: add BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT FragmentPagerAdapter contractor
public class BottomTabViewPager extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public BottomTabViewPager(FragmentManager manager) {
super(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void addTabs(String title) {
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
// return null;
}
}
// step 2: You can try like this :
public class MyFragment extends Fragment {
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ui, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
/**
* Load your stuffs here.
*/
}
}

support FragmentPagerAdapter holds reference to old fragments

I have narrowed my problem down to being a problem with the FragmentManager retaining instances of old fragments and my viewpager being out of sync with my FragmentManager. See this issue: http://code.google.com/p/android/issues/detail?id=19211#makechanges. I still have no clue how to solve this. Any suggestions?
I have tried to debug this for a long time and any help would be greatly appreciated. I am using a FragmentPagerAdapter which accepts a list of fragments like so:
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
...
new PagerAdapter(getSupportFragmentManager(), fragments);
The implementation is standard. I am using ActionBarSherlock and v4 computability library for Fragments.
My problem is that after leaving the app and opening several other applications and coming back, the fragments lose their reference back to the FragmentActivity (ie. getActivity() == null). I can not figure out why this is happening. I tried to manually set setRetainInstance(true); but this does not help. I figured that this happens when my FragmentActivity gets destroyed, however this still happens if I open the app before I get the log message. Are there any ideas?
#Override
protected void onDestroy(){
Log.w(TAG, "DESTROYDESTROYDESTROYDESTROYDESTROYDESTROYDESTROY");
super.onDestroy();
}
The adapter:
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
One of my Fragments stripped but I commented everything out that's stripped and it still doesn't work.
public class MyFragment extends Fragment implements MyFragmentInterface, OnScrollListener {
...
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
handler = new Handler();
setHasOptionsMenu(true);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.w(TAG,"ATTACHATTACHATTACHATTACHATTACH");
context = activity;
if(context== null){
Log.e("IS NULL", "NULLNULLNULLNULLNULLNULLNULLNULLNULLNULLNULL");
}else{
Log.d("IS NOT NULL", "NOTNOTNOTNOTNOTNOTNOTNOT");
}
}
#Override
public void onActivityCreated(Bundle savedState) {
super.onActivityCreated(savedState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.my_fragment,container, false);
return v;
}
#Override
public void onResume(){
super.onResume();
}
private void callService(){
// do not call another service is already running
if(startLoad || !canSet) return;
// set flag
startLoad = true;
canSet = false;
// show the bottom spinner
addFooter();
Intent intent = new Intent(context, MyService.class);
intent.putExtra(MyService.STATUS_RECEIVER, resultReceiver);
context.startService(intent);
}
private ResultReceiver resultReceiver = new ResultReceiver(null) {
#Override
protected void onReceiveResult(int resultCode, final Bundle resultData) {
boolean isSet = false;
if(resultData!=null)
if(resultData.containsKey(MyService.STATUS_FINISHED_GET)){
if(resultData.getBoolean(MyService.STATUS_FINISHED_GET)){
removeFooter();
startLoad = false;
isSet = true;
}
}
switch(resultCode){
case MyService.STATUS_FINISHED:
stopSpinning();
break;
case SyncService.STATUS_RUNNING:
break;
case SyncService.STATUS_ERROR:
break;
}
}
};
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.activity, menu);
}
#Override
public void onPause(){
super.onPause();
}
public void onScroll(AbsListView arg0, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = /* maybe add a padding */
firstVisible + visibleCount >= totalCount;
boolean away = firstVisible+ visibleCount <= totalCount - visibleCount;
if(away){
// startLoad can now be set again
canSet = true;
}
if(loadMore)
}
public void onScrollStateChanged(AbsListView arg0, int state) {
switch(state){
case OnScrollListener.SCROLL_STATE_FLING:
adapter.setLoad(false);
lastState = OnScrollListener.SCROLL_STATE_FLING;
break;
case OnScrollListener.SCROLL_STATE_IDLE:
adapter.setLoad(true);
if(lastState == SCROLL_STATE_FLING){
// load the images on screen
}
lastState = OnScrollListener.SCROLL_STATE_IDLE;
break;
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
adapter.setLoad(true);
if(lastState == SCROLL_STATE_FLING){
// load the images on screen
}
lastState = OnScrollListener.SCROLL_STATE_TOUCH_SCROLL;
break;
}
}
#Override
public void onDetach(){
super.onDetach();
if(this.adapter!=null)
this.adapter.clearContext();
Log.w(TAG, "DETACHEDDETACHEDDETACHEDDETACHEDDETACHEDDETACHED");
}
public void update(final int id, String name) {
if(name!=null){
getActivity().getSupportActionBar().setTitle(name);
}
}
}
The update method is called when a user interacts with a different fragment and the getActivity is returning null. Here is the method the other fragment is calling:
((MyFragment) pagerAdapter.getItem(1)).update(id, name);
I believe that when the app is destroyed then created again instead of just starting the app up to the default fragment the app starts up and then viewpager navigates to the last known page. This seems strange, shouldn't the app just load to the default fragment?
You are running into a problem because you are instantiating and keeping references to your fragments outside of PagerAdapter.getItem, and are trying to use those references independently of the ViewPager. As Seraph says, you do have guarantees that a fragment has been instantiated/added in a ViewPager at a particular time - this should be considered an implementation detail. A ViewPager does lazy loading of its pages; by default it only loads the current page, and the one to the left and right.
If you put your app into the background, the fragments that have been added to the fragment manager are saved automatically. Even if your app is killed, this information is restored when you relaunch your app.
Now consider that you have viewed a few pages, Fragments A, B and C. You know that these have been added to the fragment manager. Because you are using FragmentPagerAdapter and not FragmentStatePagerAdapter, these fragments will still be added (but potentially detached) when you scroll to other pages.
Consider that you then background your application, and then it gets killed. When you come back, Android will remember that you used to have Fragments A, B and C in the fragment manager and so it recreates them for you and then adds them. However, the ones that are added to the fragment manager now are NOT the ones you have in your fragments list in your Activity.
The FragmentPagerAdapter will not try to call getPosition if there is already a fragment added for that particular page position. In fact, since the fragment recreated by Android will never be removed, you have no hope of replacing it with a call to getPosition. Getting a handle on it is also pretty difficult to obtain a reference to it because it was added with a tag that is unknown to you. This is by design; you are discouraged from messing with the fragments that the view pager is managing. You should be performing all your actions within a fragment, communicating with the activity, and requesting to switch to a particular page, if necessary.
Now, back to your problem with the missing activity. Calling pagerAdapter.getItem(1)).update(id, name) after all of this has happened returns you the fragment in your list, which has yet to be added to the fragment manager, and so it will not have an Activity reference. I would that suggest your update method should modify some shared data structure (possibly managed by the activity), and then when you move to a particular page it can draw itself based on this updated data.
I found simple solution which worked for me.
Make your fragment adapter extends FragmentStatePagerAdapter instead of FragmentPagerAdapter and override method onSave to return null
#Override
public Parcelable saveState()
{
return null;
}
This prevent android from recreating fragment
One day later I found another and better solution.
Call setRetainInstance(true) for all your fragments and save references to them somewhere. I did that in static variable in my activity, because it's declared as singleTask and fragments can stay the same all the time.
This way android not recreate fragments but use same instances.
I solved this issue by accessing my fragments directly through the FragmentManager instead of via the FragmentPagerAdapter like so. First I need to figure out the tag of the fragment auto generated by the FragmentPagerAdapter...
private String getFragmentTag(int pos){
return "android:switcher:"+R.id.viewpager+":"+pos;
}
Then I simply get a reference to that fragment and do what I need like so...
Fragment f = this.getSupportFragmentManager().findFragmentByTag(getFragmentTag(1));
((MyFragmentInterface) f).update(id, name);
viewPager.setCurrentItem(1, true);
Inside my fragments I set the setRetainInstance(false); so that I can manually add values to the savedInstanceState bundle.
#Override
public void onSaveInstanceState(Bundle outState) {
if(this.my !=null)
outState.putInt("myId", this.my.getId());
super.onSaveInstanceState(outState);
}
and then in the OnCreate i grab that key and restore the state of the fragment as necessary. An easy solution which was hard (for me at least) to figure out.
Global working tested solution.
getSupportFragmentManager() keeps the null reference some times and View pager does not create new since it find reference to same fragment. So to over come this use getChildFragmentManager() solves problem in simple way.
Don't do this:
new PagerAdapter(getSupportFragmentManager(), fragments);
Do this:
new PagerAdapter(getChildFragmentManager() , fragments);
Do not try to interact between fragments in ViewPager. You cannot guarantee that other fragment attached or even exists. Istead of changing actionbar title from fragment, you can do it from your activity. Use standart interface pattern for this:
public interface UpdateCallback
{
void update(String name);
}
public class MyActivity extends FragmentActivity implements UpdateCallback
{
#Override
public void update(String name)
{
getSupportActionBar().setTitle(name);
}
}
public class MyFragment extends Fragment
{
private UpdateCallback callback;
#Override
public void onAttach(SupportActivity activity)
{
super.onAttach(activity);
callback = (UpdateCallback) activity;
}
#Override
public void onDetach()
{
super.onDetach();
callback = null;
}
public void updateActionbar(String name)
{
if(callback != null)
callback.update(name);
}
}
You can remove the fragments when destroy the viewpager, in my case, I removed them on onDestroyView() of my fragment:
#Override
public void onDestroyView() {
if (getChildFragmentManager().getFragments() != null) {
for (Fragment fragment : getChildFragmentManager().getFragments()) {
getChildFragmentManager().beginTransaction().remove(fragment).commitAllowingStateLoss();
}
}
super.onDestroyView();
}
After a few hours of looking for a similar issue I think a have another solution. This one at least it worked for me and I only have to changed a couple of lines.
This is the problem I had, I have an activity with a view pager that uses a FragmentStatePagerAdapter with two Fragments. Everything works fine until I force the activity to get destroyed (developer options) or I rotate the screen. I do keep a reference to the two fragments after they get created inside the method getItem.
At that point the activity will be created again and everything works fine at this point but I have lost the reference to my fragmetns as getItem doesn't' get called again.
This is how I fixed that problem, inside the FragmentStatePagerAdapter:
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object aux = super.instantiateItem(container, position);
//Update the references to the Fragments we have on the view pager
if(position==0){
fragTabOne = (FragOffersList)aux;
}
else{
fragTabTwo = (FragOffersList) aux;
}
return aux;
}
You won't get a call on getItem again if the adapter already has a reference to it internally, and you shouldn't change that. Instead you can get the fragment it's being used by looking at this other method instantiateItem() which will be called for each of your fragments.
Hope that helps anyone.
Since people don't tend to read comments, here is an answer that mostly duplicates what I wrote here:
the root cause of the issue is the fact that android system does not call getItem to obtain fragments that are actually displayed, but instantiateItem. This method first tries to lookup and reuse a fragment instance for a given tab in FragmentManager. Only if this lookup fails (which happens only the first time when FragmentManager is newly created) then getItem is called. It is for obvious reasons not to recreate fragments (that may be heavy) for example each time a user rotates his device.
To solve this, instead of creating fragments with Fragment.instantiate in your activity, you should do it with pagerAdapter.instantiateItem and all these calls should be surrounded by startUpdate/finishUpdate method calls that start/commit fragment transaction respectively. getItem should be the place where fragments are really created using their respective constructors.
List<Fragment> fragments = new Vector<Fragment>();
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
((TabLayout) findViewById(R.id.tabs)).setupWithViewPager(viewPager);
adapter.startUpdate(viewPager);
fragments.add(adapter.instantiateItem(viewPager, 0));
fragments.add(adapter.instantiateItem(viewPager, 1));
// and so on if you have more tabs...
adapter.finishUpdate(viewPager);
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager manager) {super(manager);}
#Override public int getCount() {return 2;}
#Override public Fragment getItem(int position) {
if (position == 0) return new Fragment0();
if (position == 1) return new Fragment1();
return null; // or throw some exception
}
#Override public CharSequence getPageTitle(int position) {
if (position == 0) return getString(R.string.tab0);
if (position == 1) return getString(R.string.tab1);
return null; // or throw some exception
}
}
Since the FragmentManager will take care of restoring your Fragments for you as soon as the onResume() method is called I have the fragment call out to the activity and add itself to a list. In my instance I am storing all of this in my PagerAdapter implementation. Each fragment knows it's position because it is added to the fragment arguments on creation. Now whenever I need to manipulate a fragment at a specific index all I have to do is use the list from my adapter.
The following is an example of an Adapter for a custom ViewPager that will grow the fragment as it moves into focus, and scale it down as it moves out of focus. Besides the Adapter and Fragment classes I have here all you need is for the parent activity to be able to reference the adapter variable and you are set.
Adapter
public class GrowPagerAdapter extends FragmentPagerAdapter implements OnPageChangeListener, OnScrollChangedListener {
public final String TAG = this.getClass().getSimpleName();
private final int COUNT = 4;
public static final float BASE_SIZE = 0.8f;
public static final float BASE_ALPHA = 0.8f;
private int mCurrentPage = 0;
private boolean mScrollingLeft;
private List<SummaryTabletFragment> mFragments;
public int getCurrentPage() {
return mCurrentPage;
}
public void addFragment(SummaryTabletFragment fragment) {
mFragments.add(fragment.getPosition(), fragment);
}
public GrowPagerAdapter(FragmentManager fm) {
super(fm);
mFragments = new ArrayList<SummaryTabletFragment>();
}
#Override
public int getCount() {
return COUNT;
}
#Override
public Fragment getItem(int position) {
return SummaryTabletFragment.newInstance(position);
}
#Override
public void onPageScrollStateChanged(int state) {}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
adjustSize(position, positionOffset);
}
#Override
public void onPageSelected(int position) {
mCurrentPage = position;
}
/**
* Used to adjust the size of each view in the viewpager as the user
* scrolls. This provides the effect of children scaling down as they
* are moved out and back to full size as they come into focus.
*
* #param position
* #param percent
*/
private void adjustSize(int position, float percent) {
position += (mScrollingLeft ? 1 : 0);
int secondary = position + (mScrollingLeft ? -1 : 1);
int tertiary = position + (mScrollingLeft ? 1 : -1);
float scaleUp = mScrollingLeft ? percent : 1.0f - percent;
float scaleDown = mScrollingLeft ? 1.0f - percent : percent;
float percentOut = scaleUp > BASE_ALPHA ? BASE_ALPHA : scaleUp;
float percentIn = scaleDown > BASE_ALPHA ? BASE_ALPHA : scaleDown;
if (scaleUp < BASE_SIZE)
scaleUp = BASE_SIZE;
if (scaleDown < BASE_SIZE)
scaleDown = BASE_SIZE;
// Adjust the fragments that are, or will be, on screen
SummaryTabletFragment current = (position < mFragments.size()) ? mFragments.get(position) : null;
SummaryTabletFragment next = (secondary < mFragments.size() && secondary > -1) ? mFragments.get(secondary) : null;
SummaryTabletFragment afterNext = (tertiary < mFragments.size() && tertiary > -1) ? mFragments.get(tertiary) : null;
if (current != null && next != null) {
// Apply the adjustments to each fragment
current.transitionFragment(percentIn, scaleUp);
next.transitionFragment(percentOut, scaleDown);
if (afterNext != null) {
afterNext.transitionFragment(BASE_ALPHA, BASE_SIZE);
}
}
}
#Override
public void onScrollChanged(int l, int t, int oldl, int oldt) {
// Keep track of which direction we are scrolling
mScrollingLeft = (oldl - l) < 0;
}
}
Fragment
public class SummaryTabletFragment extends BaseTabletFragment {
public final String TAG = this.getClass().getSimpleName();
private final float SCALE_SIZE = 0.8f;
private RelativeLayout mBackground, mCover;
private TextView mTitle;
private VerticalTextView mLeft, mRight;
private String mTitleText;
private Integer mColor;
private boolean mInit = false;
private Float mScale, mPercent;
private GrowPagerAdapter mAdapter;
private int mCurrentPosition = 0;
public String getTitleText() {
return mTitleText;
}
public void setTitleText(String titleText) {
this.mTitleText = titleText;
}
public static SummaryTabletFragment newInstance(int position) {
SummaryTabletFragment fragment = new SummaryTabletFragment();
fragment.setRetainInstance(true);
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mRoot = inflater.inflate(R.layout.tablet_dummy_view, null);
setupViews();
configureView();
return mRoot;
}
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (savedInstanceState != null) {
mColor = savedInstanceState.getInt("color", Color.BLACK);
}
configureView();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("color", mColor);
super.onSaveInstanceState(outState);
}
#Override
public int getPosition() {
return getArguments().getInt("position", -1);
}
#Override
public void setPosition(int position) {
getArguments().putInt("position", position);
}
public void onResume() {
super.onResume();
mAdapter = mActivity.getPagerAdapter();
mAdapter.addFragment(this);
mCurrentPosition = mAdapter.getCurrentPage();
if ((getPosition() == (mCurrentPosition + 1) || getPosition() == (mCurrentPosition - 1)) && !mInit) {
mInit = true;
transitionFragment(GrowPagerAdapter.BASE_ALPHA, GrowPagerAdapter.BASE_SIZE);
return;
}
if (getPosition() == mCurrentPosition && !mInit) {
mInit = true;
transitionFragment(0.00f, 1.0f);
}
}
private void setupViews() {
mCover = (RelativeLayout) mRoot.findViewById(R.id.cover);
mLeft = (VerticalTextView) mRoot.findViewById(R.id.title_left);
mRight = (VerticalTextView) mRoot.findViewById(R.id.title_right);
mBackground = (RelativeLayout) mRoot.findViewById(R.id.root);
mTitle = (TextView) mRoot.findViewById(R.id.title);
}
private void configureView() {
Fonts.applyPrimaryBoldFont(mLeft, 15);
Fonts.applyPrimaryBoldFont(mRight, 15);
float[] size = UiUtils.getScreenMeasurements(mActivity);
int width = (int) (size[0] * SCALE_SIZE);
int height = (int) (size[1] * SCALE_SIZE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
mBackground.setLayoutParams(params);
if (mScale != null)
transitionFragment(mPercent, mScale);
setRandomBackground();
setTitleText("Fragment " + getPosition());
mTitle.setText(getTitleText().toUpperCase());
mLeft.setText(getTitleText().toUpperCase());
mRight.setText(getTitleText().toUpperCase());
mLeft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mActivity.showNextPage();
}
});
mRight.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mActivity.showPrevPage();
}
});
}
private void setRandomBackground() {
if (mColor == null) {
Random r = new Random();
mColor = Color.rgb(r.nextInt(255), r.nextInt(255), r.nextInt(255));
}
mBackground.setBackgroundColor(mColor);
}
public void transitionFragment(float percent, float scale) {
this.mScale = scale;
this.mPercent = percent;
if (getView() != null && mCover != null) {
getView().setScaleX(scale);
getView().setScaleY(scale);
mCover.setAlpha(percent);
mCover.setVisibility((percent <= 0.05f) ? View.GONE : View.VISIBLE);
}
}
#Override
public String getFragmentTitle() {
return null;
}
}
My solution: I set almost every View as static. Now my app interacts perfect. Being able to call the static methods from everywhere is maybe not a good style, but why to play around with code that doesn't work? I read a lot of questions and their answers here on SO and no solution brought success (for me).
I know it can leak the memory, and waste heap, and my code will not be fit on other projects, but I don't feel scared about this - I tested the app on different devices and conditions, no problems at all, the Android Platform seems to be able handle this. The UI gets refreshed every second and even on a S2 ICS (4.0.3) device the app is able to handle thousands of geo-markers.
I faced the same issue but my ViewPager was inside a TopFragment which created and set an adapter using setAdapter(new FragmentPagerAdapter(getChildFragmentManager())).
I fixed this issue by overriding onAttachFragment(Fragment childFragment) in the TopFragment like this:
#Override
public void onAttachFragment(Fragment childFragment) {
if (childFragment instanceof OnboardingDiamondsFragment) {
mChildFragment = (ChildFragment) childFragment;
}
super.onAttachFragment(childFragment);
}
As known already (see answers above), when the childFragmentManager recreate itself, it also create the fragments which were inside the viewPager.
The important part is that after that, he calls onAttachFragment and now we have a reference to the new recreated fragment!
Hope this will help anyone getting this old Q like me :)
I solved the problem by saving the fragments in SparceArray:
public abstract class SaveFragmentsPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> fragments = new SparseArray<>();
public SaveFragmentsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
fragments.append(position, fragment);
return fragment;
}
#Nullable
public Fragment getFragmentByPosition(int position){
return fragments.get(position);
}
}
Just so you know...
Adding to the litany of woes with these classes, there is a rather interesting bug that's worth sharing.
I'm using a ViewPager to navigate a tree of items (select an item and the view pager animates scrolling to the right, and the next branch appears, navigate back, and the ViewPager scrolls in the opposite direction to return to the previous node).
The problem arises when I push and pop fragments off the end of the FragmentStatePagerAdapter. It's smart enough to notice that the items change, and smart enough to create and replace a fragment when the item has changed. But not smart enough to discard the fragment state, or smart enough to trim the internally saved fragment states when the adapter size changes. So when you pop an item, and push a new one onto the end, the fragment for the new item gets the saved state of the fragment for the old item, which caused absolute havoc in my code. My fragments carry data that may require a lot of work to refetch from the internet, so not saving state really wasn't an option.
I don't have a clean workaround. I used something like this:
public void onSaveInstanceState(Bundle outState) {
IFragmentListener listener = (IFragmentListener)getActivity();
if (listener!= null)
{
if (!listener.isStillInTheAdapter(this.getAdapterItem()))
{
return; // return empty state.
}
}
super.onSaveInstanceState(outState);
// normal saving of state for flips and
// paging out of the activity follows
....
}
An imperfect solution because the new fragment instance still gets a savedState Bundle, but at least it doesn't carry stale data.

Categories

Resources