I have a fragment with TabLayout, which looks like this:
Code, where it is created:
public class CalendarActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_calendar);
SimpleDateFormat sdf = new SimpleDateFormat("EEE dd-MM", new Locale("en", "GB"));
TabLayout tabLayout = findViewById(R.id.tabs);
final ViewPager viewPager = findViewById(R.id.viewPager);
tabLayout.addTab(tabLayout.newTab().setText("today"));
tabLayout.addTab(tabLayout.newTab().setText("tomorrow"));
tabLayout.addTab(tabLayout.newTab().setText(sdf.format(new Date(((new Date()).getTime() + 2*86400000)))));
tabLayout.addTab(tabLayout.newTab().setText(sdf.format(new Date(((new Date()).getTime() + 3*86400000)))));
tabLayout.addTab(tabLayout.newTab().setText(sdf.format(new Date(((new Date()).getTime() + 4*86400000)))));
tabLayout.addTab(tabLayout.newTab().setText(sdf.format(new Date(((new Date()).getTime() + 5*86400000)))));
tabLayout.addTab(tabLayout.newTab().setText(sdf.format(new Date(((new Date()).getTime() + 6*86400000)))));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
PageAdapterCalendar adapter = new PageAdapterCalendar (getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
Adapter code:
public class PageAdapterCalendar extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapterCalendar (FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
fragment = CalendarFragment.newInstance();
break;
}
return fragment;
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
newinstance() in Calendar fragment:
public static Fragment newInstance() {
CalendarFragment fragment = new CalendarFragment();
return fragment;
}
I need each of my tabs to behave the same and use the same layout, but I only need to send them info about the date (same as it's in their title), so they would get different data from database. I have tried bundles and tags, but it didn't work as I expected - Bundles were added all to each tab and tags are not loaded on onCreate() part (I think?), so they were empty.
In your newInstance method try to pass in the relevant information for each fragment you are creating as parameters. You just need to pass in what little information is necessary so that fragment knows where to get its data from in your database. Then from there create a bundle (eg mBundle) and put all those values into that bundle and call fragment.setArguments(mBundle). Then in your fragment onCreate method parse that bundle to get your data and go from there.
It seems like a lot of steps but this method ensures that the data persists across all lifecycle events
For an example see Best practice for instantiating a new Android Fragment
Related
I have used Tab Control and RecyclerView together in Android. The way it functions is I have SearchBar in the toolbar. When the user enters the search query in the search bar. Upon hitting the search button, tab's Fragments are supposed to be loaded with data. Issues are as follows.
1) Tabs icon disappear
2) When debugging through the code found (Since I am using ViewPager with Tab Layout to implement Tabs in android) that getItem method of PagerAdapter class is called twice every time getItem is triggered.
I am stuck and don't know what to do. Not much help online as well.
1) Tab initialization Code:-
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.craigslist_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.kijiji_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.letgo_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.varagesale_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.facebook_new1));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
drawerLayout = findViewById(R.id.drawer_layout);
}
#Override
public boolean onQueryTextSubmit(String query) {
//loadRecyclerViewData(query);
Bundle bundle = new Bundle();
bundle.putString("searchText", query);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), bundle);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return true;
}
2) PagerAdapter:-
public class PageAdapter extends FragmentStatePagerAdapter {
int mNoofTabs;
Bundle bundle;
public PageAdapter(FragmentManager fragmentManager, int NumberOfTabs, Bundle bundle)
{
super(fragmentManager);
this.mNoofTabs = NumberOfTabs;
this.bundle = bundle;
}
#Override
public Fragment getItem(int i) {
switch(i)
{
case 0 :
CraigslistFragment tab1 = new CraigslistFragment();
tab1.setArguments(bundle);
return tab1;
case 1:
KijijiFragment tab2 = new KijijiFragment();
tab2.setArguments(bundle);
return tab2;
case 2:
letgoFragment tab3 = new letgoFragment();
tab3.setArguments(bundle);
return tab3;
case 3:
VaragesaleFragment tab4 = new VaragesaleFragment();
tab4.setArguments(bundle);
return tab4;
case 4:
FacebookFragment tab5 = new FacebookFragment();
tab5.setArguments(bundle);
return tab5;
default:
return null;
}
}
#Override
public int getCount() {
return mNoofTabs;
}
}
I am building this Android Application and I have this Activity where I have a ViewPager that hosts 4 different Fragments. The user can swipe among those fragments and see their data. I also have a menu where the user can delete or send records displayed on the 4 Fragments.
In order to figure out which fragment is active, I run this code (from the Activity where the viewPager is):
int activeItem = viewPager.getCurrentItem();
Log.e(TAG, "activeItem = " + activeItem);
Fragment fragment = this.getSupportFragmentManager().getFragments().get(activeItem);
String fragmentName = fragment.getClass().getSimpleName();
Log.e(TAG, "fragment name = " + fragmentName);
if(activeItem == 0) {
showDialog("Confirm Send", "Would you like to send the checked items?",
actionSend, RecordsSent, fragment);
}
else{
showDialog("Confirm Send", "Would you like to send the checked items?",
actionSend, RecordsPending, fragment);
}
What I do is I get the active item, then get the fragment at that index (using getSupportFragmentManager()). And then based on what the active item is, I have a good idea which Fragment is active.
This was working for quite some time until I added another fragment and all of a sudden, I was getting a ClassCastException. Because in my showDialog function, I do something like:
RecordsSent rsFragment = (RecordsSent) fragment;
And what was happening is that it was sending the wrong fragment! My fragments are:
RecordsSent
RecordsPending
RecordsSales
RecordsNews
I was getting a Class Cast error because I was casting RecordsPending to RecordsSent and vice versa. I then listed my fragments with:
Log.e(TAG, "fragments = " + this.getSupportFragmentManager().getFragments().toString());
And then it showed RecordsPending first then RecordsSent. No wonder I was getting a ClassCastException. getCurrentItem was returning 0, and item 0 in the supportFragmentManager is RecordsPending instead of RecordsSent.
I don't know what prompted the switch between the indices of my Fragments, which makes this conundrum all the more puzzling.
Here's the code I used to initialize the Fragments.
TextView tv1 = createTab("Sent", new ColorDrawable(Color.parseColor("#006633")));
TextView tv2 = createTab("Pending", new ColorDrawable(Color.parseColor("#CCCC00")));
TextView tv3 = createTab("Daily Sales Report", new ColorDrawable(Color.parseColor("#F7C05F")));
TextView tv4 = createTab("News Records", new ColorDrawable(Color.parseColor("#B72153")));
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setCustomView(tv1).setTag("Sent"));
tabLayout.addTab(tabLayout.newTab().setCustomView(tv2).setTag("Pending"));
tabLayout.addTab(tabLayout.newTab().setCustomView(tv3).setTag("Sales"));
tabLayout.addTab(tabLayout.newTab().setCustomView(tv4).setTag("News"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//more code here
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new PagerAdapter (getSupportFragmentManager(), tabLayout.getTabCount());
Log.e(TAG, "tab count = " + tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
My PagerAdapter class looks like this:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
RecordsSent tab1 = new RecordsSent();
return tab1;
case 1:
RecordsPending tab2 = new RecordsPending();
return tab2;
case 2:
RecordsSales tab3 = new RecordsSales();
return tab3;
case 3:
RecordsNews tab4 = new RecordsNews();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
As you can see, the first item is RecordsSent, then RecordsPending. I do not know why the supportFragmentManager returns the reverse order.
I tried:
android.support.v4.app.Fragment fragment = getVisibleFragment();
String fragmentName = fragment.getClass().getSimpleName();
but it still returns the wrong fragment type.
I also tried to do this inside my if-else blocks:
if(activeItem == 0) {
Log.e(TAG, "fragment is records sent");
fragment = fm.findFragmentByTag("Sent");
showDialog(title, message,
actionDelete, RecordsSent, fragment);
}
else{
//I use "Pending" here
}
However, I get a null pointer exception when I force it.
This problem is really frustrating because it was working days ago and then suddenly it isn't.
I have setup a list of fragments using TabLayout and ViewPager on MainActivity as such
public class MainActivity extends AppCompatActivity implements Fragment1.OnFragmentInteractionListener, Fragment2.OnFragmentInteractionListener, Fragment3.OnFragmentInteractionListener, Fragment4.OnFragmentInteractionListener
, Fragment5.OnFragmentInteractionListener{
TabLayout tabLayout;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapater(getSupportFragmentManager(), getApplicationContext()));
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#51ffff"));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
switch (tab.getPosition()) {
case 0:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#ced21f"));
break;
case 1:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#51ffff"));
break;
case 2:
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private class CustomAdapater extends FragmentPagerAdapter {
private String fragments[] = {"Control", "Connection", "Log", "Others", "Others2"};
public CustomAdapater(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment1();
case 1:
return new Fragment3();
case 2:
return new Fragment2();
case 3:
return new Fragment4();
case 4:
return new Fragment5();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
}
Somehow when I transit from Fragment1 to Fragment3 and back to Fragment1, the views on Fragment1 gets reset to original state(Like it was just created).
This only happens if I transit 2 fragment away from the current Fragment. For example 2->4 or 3->1.
Everything is fine if the transition is next to each other, for example 2->3 or 1->2.
This is my first android app so do pardon me.
It seems like it is creating a new fragment instead loading of existing ones
Your fragment get destroyed due to the fact that by default viewpager retain only one fragment at a time while moving around so you can simply use
viewPager.setOffscreenPageLimit(no_of_fragment_to_retain);
or
viewPager.setOffscreenPageLimit(3); // in your case
so when you come back from 4->1 or 3->1 you will get the previous stored state of your fragment. link to docs
First :
viewPager.setAdapter(new CustomAdapater(getSupportFragmentManager(), getBaseContext()));
Now see : in get Item method of View pager evrytime when you go to new tab a new instance of fragment is created So the previous view is lost . You should retain state in your fragment class.
or a simple solution is use FragmentstatepagerAdapter instead of FragmentPagerAdapter in your Adapter class.
Let me know if it helps
I have a viewpager with 5 tabs , each tab is fragment showing different data to user , each fragment have recycleview inside itself , and i need to re insert updated data into the recyclerview when user change the tab, and I need to update the view
Every time I swipe to a tab, a new instance of the fragment in that tab needs to load so that data will be updated.
I have tried:
1- I used FragmentStatePagerAdapter (nothing happens)
2- I Override getItemPosition method to return PagerAdapter.POSITION_NONE; (nothing happens)
3- setOffscreenPageLimit(0) (Nothing happens)
4- refresh function inside each fragment to be called onTabSelected
(gives nullPointerException)
How can i recreate fragment from scratch each time user change the tab
i really need to know.
I have been struggling with this problem for a week with no progress. I appreciate any help, be it a hint, a comment, a suggestion.
Let me know what code should I post, Thanks.
Edit:
my codes:
MainActivity:
public class Sefaresh_activity3 extends AppCompatActivity implements Serializable, Sefaresh3_interface {
Context context;
Toolbar mtoolbar;
private List<Food> food_list = new ArrayList<>();
MyPagerAdapter adapter;
Custom_TabLayout mTabLayout;
ViewPager mpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sefaresh_activity3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
}
context = this;
sqlHelper = new SqlHelper(this);
setupTabs();
private void setupTabs() {
mtoolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mtoolbar);
SpannableString s = new SpannableString(getTitle());
s.setSpan(new TypefaceSpan(this, "IRAN Sans Bold.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setTitle(s);
try {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} catch (Exception e) {
L.m("something is wrong in toolbar section");
}
adapter = new MyPagerAdapter(getSupportFragmentManager());
mTabLayout = (Custom_TabLayout) findViewById(R.id.tab_layout);
mpager = (ViewPager) findViewById(R.id.viewpager);
mpager.setAdapter(adapter);
mTabLayout.setTabsFromPagerAdapter(adapter);
mTabLayout.setupWithViewPager(mpager);
mpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
L.m("tab selected" + tab.getPosition());
mpager.setCurrentItem(tab.getPosition());
// Sefaresh3_fragment all_fragment = (Sefaresh3_fragment) adapter.getFragment_all();
// sefaresh3_fragment.onRefresh();
// Sefaresh3_fragment sefaresh3_fragment = (Sefaresh3_fragment) adapter.fragment_all;
// adapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
// public ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
Fragment fragment_all;
Fragment fragment_pizza;
Fragment fragment_sandwich;
Fragment fragment_salad;
Fragment fragment_coca;
public Fragment getFragment_coca() {
return fragment_coca;
}
public Fragment getFragment_all() {
return fragment_all;
}
public Fragment getFragment_pizza() {
return fragment_pizza;
}
public Fragment getFragment_sandwich() {
return fragment_sandwich;
}
public Fragment getFragment_salad() {
return fragment_salad;
}
String[] tabs = {
"products",
"new products",
"featured",
"star",
"star2"
};
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
public MyPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.sefaresh3_tabs);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int num) {
Fragment fragment = null;
orders = new Orders();
orders.setOrders(all_orders);
switch (num) {
case 0:
// fragment_all = Sefaresh3_fragment.newInstance("all", "");
// return new Sefaresh3_fragment().newInstance("all","");
return Sefaresh3_fragment.newInstance("all","");
case 1:
fragment_pizza = Sefaresh3_fragment.newInstance("pizza", "");
return fragment_pizza;
case 2:
fragment_sandwich = Sefaresh3_fragment.newInstance("sandwich", "");
return fragment_sandwich;
case 3:
fragment_salad = Sefaresh3_fragment.newInstance("salad", "");
return fragment_salad;
case 4:
fragment_coca = Sefaresh3_fragment.newInstance("coca", "");
return fragment_coca;
default:
return fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 5;
}
}
thanks for everybody suggestions , after one week struggling with this problem I found the solution.
I tried several methods but finally I just found the solution.
I used Broadcast receiver to tell the fragment update the list , and every time I need to update the fragments to update the data list , I call the broadcaster. its awesome and it works well
If anyone had the same problem I will be happy to help him :) thanks.
I'm using ActionBarActivity to create 5 tabs. I have used ViewPager to swipe between the 5 tabs using SectionsPagerAdapter which extends FragmentPagerAdapter. Each tab has a fragment with an asynctask called in oncreateview method. When I'm in one fragment, asynctask in other fragment is being called.
I tried using toast messages in oncreateview method is each fragment instead of asynctask. But wrong toast messages are being fired in wrong fragment.
Oncreate method code:
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager_exp);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
actionBar.setSelectedNavigationItem(position);
actionBar.setTitle(getHomePageTitle(position));
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
{
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setIcon(getPagedrawable(i))
.setTabListener(this));
}
// Adapter class code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
Fragment1 f1 = new Fragment1();
return f1;
case 1:
Fragment2 f2 = new Fragment2();
return f2;
case 2:
Fragment3 f3 = new Fragment3();
return f3;
case 3:
Fragment4 f4 = new Fragment4();
return f4;
case 4:
Fragment5 f5 = new Fragment5();
return f5;
}
return null;
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
Fragemnt class code :
public class F1 extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.f1,container, false);
Toast.makeText(getActivity(), "F1", Toast.LENGTH_SHORT).show();
return view;
}
}
The FragmentPagerAdapter keeps additional fragments, besides the one shown, in resumed state. The solution is to implement a custom OnPageChangeListener and create a new method for when the fragment is shown.
1) Create LifecycleManager Interface
The interface will have two methods and each ViewPager’s Fragment will implement it. These methods Are as follows:
public interface FragmentLifecycle {
public void onPauseFragment();
public void onResumeFragment();
}
2) Let each Fragment implement the interface
Add iplements statement for each class declaration:
public class FragmentBlue extends Fragment implements FragmentLifecycle
public class FragmentGreen extends Fragment implements FragmentLifecycle
public class FragmentPink extends Fragment implements FragmentLifecycle
3) Implement interface methods in each fragment
In order to check that it really works as expected, I will just log the method call and show Toast:
#Override
public void onPauseFragment() {
Log.i(TAG, "onPauseFragment()");
Toast.makeText(getActivity(), "onPauseFragment():" + TAG, Toast.LENGTH_SHORT).show();
}
#Override
public void onResumeFragment() {
Log.i(TAG, "onResumeFragment()");
Toast.makeText(getActivity(), "onResumeFragment():" + TAG, Toast.LENGTH_SHORT).show();
}
4) Call interface methods on ViewPager page change
You can set OnPageChangeListener on ViewPager and get callback each time when ViewPager shows another page:
pager.setOnPageChangeListener(pageChangeListener);
5) Implement OnPageChangeListener to call your custom Lifecycle methods
Listener knows the new position and can call the interface method on new Fragment with the help of PagerAdapter. I can here call onResumeFragment() for new fragment and onPauseFragment() on the current one.
I need to store also the current fragment’s position (initially the current position is equal to 0), since I don’t know whether the user scrolled from left to right or from right to left. See what I mean in code:
private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
int currentPosition = 0;
#Override
public void onPageSelected(int newPosition) {
FragmentLifecycle fragmentToShow = (FragmentLifecycle)pageAdapter.getItem(newPosition);
fragmentToShow.onResumeFragment();
FragmentLifecycle fragmentToHide = (FragmentLifecycle)pageAdapter.getItem(currentPosition);
fragmentToHide.onPauseFragment();
currentPosition = newPosition;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
public void onPageScrollStateChanged(int arg0) { }
};
I didn't write the code. Full tutorial here: http://looksok.wordpress.com/2013/11/02/viewpager-with-detailed-fragment-lifecycle-onresumefragment-including-source-code/
Use this
viewPager.setOffscreenPageLimit(1); // the number of pages you want to load in background
and also a ProgressDialogue.
ViewPager creates views for fragments adjacent to your current page. This also gives you an opportunity to load any data required for the adjacent fragments. If you are using AsyncTasks to load data, using this feature will result in a better user experience. But if you need an event when a particular page is opened by the viewpager, LordRaydenMK's solution will work.
See my post on the following thread for using AsyncTasks in a ViewPager:
AsyncTask runs on each page of the ViewPager
Hi You can try by using tag of each fragment and call method of each fragment on Page Changed
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
actionBar.setTitle(getHomePageTitle(position));
Fragment f = getFragrmentManager().findFragmentByTag(
"" + position);
if (f != null)
f.refresh();
}
});
and on
#Override
public Fragment getItem(int position) {
Fragment f=null;
switch (position)
{
case 0:
f = new Fragment1();
break;
case 1:
f = new Fragment2();
break;
case 2:
f = new Fragment3();
break;
case 3:
f = new Fragment4();
break;
case 4:
f = new Fragment5();
break;
}
f.setTag(""+position);
return f;
}