ViewPager loads 2 fragments at the same time - java

So I have 2 fragments and view pager. When I click on a button to load the first fragment the second fragment also gets loaded on the same screen.
The adapter I am using:
Adapter.java:
public class Adapter extends FragmentPagerAdapter {
public Adapter(FragmentManager fm){
super(fm);
}
#NotNull
#Override
public Fragment getItem(int position){
if(position==0){
return new SettingsFragment();
}
if (position==1){
return new BlankFragment();
}
return null;
}
#Override
public int getCount(){
return 2;
}
}
Any idea what's going on here?

Pls try the following:
private void finishActivity() {
if(getActivity() != null) {
getActivity().finish();
}
}
Call the above method before launching the fragments.
finishActivity();
return new BlankFragment();

ViewPager is created to load minimum 3 pages ( 1 that user iteract with, 1 from the left, 1 from the right ), you dont need this behaviour why do use it? You can simply replace fragment in your container with animation.

Related

app crashes when swipe to new fragment and swipe back to previous fragment in tabLayout

I have a Main fragment that contains two fragments (fragment A & B), and above in the toolBar there is a search icon for search purpose. My problem is when I just only swipe between fragment A & B and use the search icon to do some search filter, the app works OK. But the problem is when I add another new fragment C in the Main fragment, after starting the app and swipe to fragment C then swipe back to fragment A or B, then click the search icon, the app crashed.
Here is the crash log
2019-03-07 22:52:10.616 28866-28866/com.example.welsenho.questfy_tw E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.welsenho.questfy_tw, PID: 28866
java.lang.ClassCastException: com.example.welsenho.questfy_tw.MainActivityFragment.MostPopularFragment cannot be cast to com.example.welsenho.questfy_tw.MainActivityFragment.MainActivityLatestArticleFragment
at com.example.welsenho.questfy_tw.MainUserActivity.MainActivity.searchFilter(MainActivity.java:303)
at com.example.welsenho.questfy_tw.MainUserActivity.MainActivity.access$200(MainActivity.java:50)
at com.example.welsenho.questfy_tw.MainUserActivity.MainActivity$1.onQueryTextChange(MainActivity.java:158)
at android.support.v7.widget.SearchView.onTextChanged(SearchView.java:1181)
at android.support.v7.widget.SearchView$10.onTextChanged(SearchView.java:1715)
at android.widget.TextView.sendOnTextChanged(TextView.java:9364)
at android.widget.TextView.setText(TextView.java:5397)
at android.widget.TextView.setText(TextView.java:5250)
at android.widget.EditText.setText(EditText.java:113)
at android.widget.TextView.setText(TextView.java:5207)
at android.support.v7.widget.SearchView.onActionViewExpanded(SearchView.java:1295)
at android.support.v7.widget.Toolbar$ExpandedActionViewMenuPresenter.expandItemActionView(Toolbar.java:2397)
It says that Fragment A cannot be cast to Fragment B, but what I don't understand is that if I did not swipe to Fragment C (Just between Fragment A & B) everything will be just fine but after swiping to Fragment C and swipe back to Fragment A or B and click the search icon then the app will crash
code for the Main Activity
private void searchFilter(String inputText, ArrayList<FirebaseDatabaseGetSet> decidedFilterList) {
Log.d("TAG", "searchFilter");
ArrayList<FirebaseDatabaseGetSet> filterList = new ArrayList<>();
if (!filterList.isEmpty()) {
filterList.clear();
}
MainActivityLatestArticleFragment latestArticleFragment;
MostPopularFragment mostPopularFragment;
MainSubjectChooseFragment mainSubjectChooseFragment;
//MainSubjectChooseFragment mainSubjectChooseFragment(Fragment C) = (MainSubjectChooseFragment) getSupportFragmentManager().getFragments().get(0).getChildFragmentManager() .getFragments().get(2);
latestArticleFragment(Fragment A) = (MainActivityLatestArticleFragment) getSupportFragmentManager().getFragments().get(0).getChildFragmentManager().getFragments().get(0);
mostPopularFragment(Fragment B) = (MostPopularFragment) getSupportFragmentManager().getFragments().get(0).getChildFragmentManager().getFragments().get(1);
Log.d("TAG", "Fragment");
for (FirebaseDatabaseGetSet firebaseDatabaseGetSet : decidedFilterList) {
if (firebaseDatabaseGetSet.getTitle().toLowerCase().contains(inputText.toLowerCase())) {
filterList.add(firebaseDatabaseGetSet);
if (currentFilterPage == 0) {
Log.d("TAG", "Fragment0");
if (latestArticleFragment != null) {
Log.d("TAG", "notNull");
if (!filterList.isEmpty()) {
Log.d("TAG", "filter");
latestArticleFragment.returnFilterList(filterList);
}
}
} else if (currentFilterPage == 1) {
Log.d("TAG", "Fragment1");
if (mostPopularFragment != null) {
if (!filterList.isEmpty()) {
mostPopularFragment.returnFilterList(filterList);
}
}
}
}
}
}
code for Main Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main_activity_tab, container, false);
tabLayout = view.findViewById(R.id.main_activity_tabLayout);
viewPager = view.findViewById(R.id.main_activity_viewpager);
viewPager.setAdapter(new MainActivityTabAdapter(getChildFragmentManager(), Locale.getDefault().getDisplayLanguage()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
mListener.getTabCurrentPage(i);
}
#Override
public void onPageSelected(int i) {
mListener.getTabCurrentPage(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
return view;
code for the adapter
#Override
public Fragment getItem(int i) {
switch (i){
case 0: return new MainActivityLatestArticleFragment();
case 1: return new MostPopularFragment();
case 2: return new MainSubjectChooseFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
if (language.equals("中文")) {
switch (position) {
case 0:
return "最新文章";
case 1:
return "熱門文章";
case 2:
return "相關科系";
}
}else {
switch (position) {
case 0:
return "Latest Article";
case 1:
return "Most Popular";
case 2:
return "Program Select";
}
}
return null;
}
code in Fragment A & B are just for only retrieving data from firebase and load into recyclerView. It says the problem was cause by this line latestArticleFragment(Fragment A) = (MainActivityLatestArticleFragment) getSupportFragmentManager().getFragments().get(0).getChildFragmentManager().getFragments().get(0); part, but I don't get it is that when I'm not trying to swipe to Fragment C everything works smoothly, but if I did swipe to Fragment C and swipe back to Fragment A & B then click the search icon the app will crashed. I have beed bothered by this problem for like 3 days already and tried some solution but it just can not work. Can anyone explain why I am having this problem and how I can fix it?
My hunch is if you set off screen page limit to more than 1, you will not face the issue. So in your MainFragment's onCreateView add the following one line:
viewPager = view.findViewById(R.id.main_activity_viewpager);
// add below line
viewpager.setOffscreenPageLimit(2)
viewPager.setAdapter(new MainActivityTabAdapter(getChildFragmentManager(), Locale.getDefault().getDisplayLanguage()));

Fragments not visible when switch tabs using ViewPager and TabLayout

I have a HostActivity that uses ViewPager and TabLayout to switch between multiple Fragments. When I switch between the tabs, the Fragments instance does get the updated data. I also see the updated data in onCreateView of the Fragment instance, but the TextView.setText does not get updated. When I check the visibility of Fragment, it always shows Invisible. How do I make the fragment visible when I switch tabs so that the view gets updated with new data? Is there something missing in the Fragment/Activity Lifecycle? I am implementing ViewPager for the first time so it will be helpful to know if I am missing something.
Fragment Class:
public class StepFragment extends Fragment { #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (getArguments() != null) {
step = getArguments().getParcelable(SELECTED_STEP);
mDescription = step.getDescription();
}
View view = inflater.inflate(R.layout.step_fragment, container, false);
ButterKnife.bind(this,view);
Log.e(TAG, "onCreateView: "+mDescription); **// THIS GETS UPDATED DATA**
tvStepDescription.setText(mDescription);
}
return view;
}
}
Here is my Host Activity:
public class StepActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step);
fragmentSelectAdapter = new StepFragmentSelectAdapter(getSupportFragmentManager(),this,steps,recipe);
mViewPager.setAdapter(fragmentSelectAdapter);
mTabLayout.setupWithViewPager(mViewPager);
stepFragment = (StepFragment) getSupportFragmentManager().findFragmentById(R.id.step_container);
if(stepFragment == null) {
stepFragment = StepFragment.newInstance(step, recipe);
stepFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.add(R.id.step_container, stepFragment)
.commit();
} else {
stepFragment = StepFragment.newInstance(step, recipe);
stepFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(R.id.step_container, stepFragment)
.commit();
}
}
}
Here is my FragmentPagerAdapter, which seems to be getting the correct data as per the tab position in getItem method:
public class StepFragmentSelectAdapter extends FragmentPagerAdapter {
...
#Override
public Fragment getItem(int position) {
**// THIS GETS UPDATED DATA**
Log.e(TAG, "getItem: \nDecr: "+steps.get(position).getDescription()+"\nVideo: "+steps.get(position).getVideoURL()+"\nImage: "+steps.get(position).getThumbnailURL());
return StepFragment.newInstance(steps.get(position),recipe);
}
#Override
public int getCount() {
if (steps == null){
return 0;
}
return steps.size();
}
...
}
As far as I could understand about the problem that you are having there, I think you should implement an onResume function in your StepFragment which will get the updated data from some source and will display this in the TextView. However, I can think of a potential problem in your StepFragmentSelectAdapter. You are creating a new instance each time you are switching the tabs.
You should have the Fragment instances created before and if you are about to pass the data among fragments, you might consider having a BroadcasReceiver or listener function by implementing an interface.
So the PagerAdapter should look something like this.
public class StepFragmentSelectAdapter extends FragmentPagerAdapter {
public ArrayList<StepFragment> stepFragments;
public StepFragmentSelectAdapter(ArrayList<Step> steps) {
stepFragments = new ArrayList<>();
for(int i = 0; i < steps.size(); i++) {
stepFragments.add(StepFragment.newInstance(steps.get(position),recipe));
}
}
...
#Override
public Fragment getItem(int position) {
**// THIS GETS UPDATED DATA**
Log.e(TAG, "getItem: \nDecr: "+steps.get(position).getDescription()+"\nVideo: "+steps.get(position).getVideoURL()+"\nImage: "+steps.get(position).getThumbnailURL());
return stepFragments.get(position);
}
#Override
public int getCount() {
if (steps == null){
return 0;
}
return steps.size();
}
...
}
Thanks for the hint. I got around this problem by replacing ActionBar with a custom ToolBar with back ImageButton and using click listener to get back to the calling activity.
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});

Sliding between fragments

I'm developing an app and currently I am trying to add ScreenSlide to it. I managed to do this using a tutorial, but usual sliding between x pages is not quite what I'm looking for.
With code provided below I can slide between 5 pages, but pages aligned in a straight line and you can't go from first page straight to 5th and vise versa.
In my app I have 4 pages. When I slide left I switch between first 2 pages, when I slide right I switch between 2 last pages. On image below you can see how my current code switches page and under it - my goal.
public class MainActivity extends FragmentActivity {
private static final int NUM_PAGES = 5;
private ViewPager mPager;
private ScreenSlidePageFragment[] pages = new ScreenSlidePageFragment[NUM_PAGES];
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_PAGES;
}
#Override
public Fragment getItem(int position) {
boolean moveRight = mPager.getCurrentItem() < position;
boolean moveLeft = mPager.getCurrentItem() > position;
switch(position){
case 5:
if(moveRight){
return geLog.w("i"
+ "Info", Integer.toString(position));
//return getPageByPosition(2);
if(moveLeft)
return getPageByPosition(2);
}
return new ScreenSlidePageFragment();
}
private Fragment getPageByPosition(int position){
int index = position - 1;
if(index < 0 || index > NUM_PAGES-1)
throw new InvalidParameterException("requested position is invalid");
if(pages[index] == null)
pages[index] = new ScreenSlidePageFragment();
return pages[index];
}
}
}
[UPDATE]
I've managed to write a code that allows me to infinitely slide to the right between 6 different pages. Left side is limited though - I can slide only to the first page(so if I'm on 1st page after I cycled 3 times to the right, I can make only 3 cycles backwards). I think I am very close to finding the solution. Any ideas?
MainActivity.java
public class MainActivity extends FragmentActivity {
private static final int NUM_PAGES = 6;
private ViewPager pager;
private PagerAdapter pagerAdapter;
private List<ScreenSlidePageFragment> slideList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
slideList = new ArrayList<ScreenSlidePageFragment>();
for (int i = 0; i<NUM_PAGES; i++){
ScreenSlidePageFragment slide = new ScreenSlidePageFragment();
slide.setIndex(i+1);
slideList.add(slide);
}
pager = (ViewPager) findViewById(R.id.pager);
pagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(pagerAdapter);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
int _pos = position % NUM_PAGES;
return slideList.get(_pos);
}
#Override
public int getCount() {
return Integer.MAX_VALUE;
}
}
}
ScreenSlidePageFragment.java
public class ScreenSlidePageFragment extends Fragment {
private int index;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup)inflater.inflate(R.layout.slide, container, false);
TextView tw = (TextView) root.findViewById(R.id.textView);
tw.setText(Integer.toString(index));
return root;
}
public void setIndex(int index){
this.index = index;
}
}
One possible workaround is not using viewpager, but creating your own custom Slider, I ended up with this solution, since ViewPager is very unflexible, like for example if you try to do something like Facebook Page app kind of thing.
Cons: you have to manage all the touches and lifecycle.
Another simpler solution for this is basically use the following API if I understand the question correctly it should be enough.
ViewPager.setCurrentItem
This is what I would do.
Since you have a finite amount of screens, I would make an array to save each instance of the ScreenSlidePageFragment you make under a corresponding index. So you can get an instance from that array by using "position". This will allow you to leverage getItem function to do something like
...
private ScreenSlidePageFragment[] pages = new ScreenSlidePageFragment[NUM_PAGES];
...
#Override
public Fragment getItem(int position) {
boolean moveRight = mPager.getCurrentItem() < position;
switch(position){
case 1:
if(moveRight)
return getPageByPosition(3);
return getPageByPosition(2);
case 2:
if(moveRight)
//case when you are in a position 3 and swipe right - return first screen
return getPageByPosition(3);
//if you're swiping left from position 1, return the next screen
return getPageByPosition(1);
case 3:
//write out the rest of your logic
...
}
}
private Fragment getPageByPosition(int position){
int index = position - 1;
if(index < 0 || index > NUM_PAGES-1)
throw new InvalidParameterException("requested position is invalid")
if(pages[index] == null)
pages[index] = new ScreenSlidePageFragment();
return pages[index];
}
Note: code not tested
Basically, you will need to write out the logic to return an existing instance of a fragment based on where you are currently and which position is requested.
You can try ViewPager.setCurrentItem
If you want to navigate to page
viewPager.setCurrentItem(PAGE_POS);
If you want to navigate to page without smooth scroll
viewPager.setCurrentItem(PAGE_POS,false);
I think it's possible to do.
1. Set ViewPager's item count to Integer.MAX_VALUE and current item to Integer.MAX_VALUE/2. It gives you ability to create fake infinite scroll.
2. Realize your logic depending on fragment on current position. It is easy if you store them in your adapter:
#Override
public Fragment getItem(int position) {
ItemFragmentRoot fragment = new ItemFragmentRoot();
mFragmentMap.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
mFragmentMap.remove(position);
}
public ItemFragmentRoot getItem(int position){
return mFragmentMap.get(position);
}
And the most difficult part, I think. Since ViewPager cache at least 1 view each side and you don't know which way user going to scroll the only one way is to manualy initialize and reinitialize appearing fragment according to scroll side. Use nested fragment inside each ItemFragmentRoot I mentioned before. All depends on how heavy your view hierarchy.
I can write more code later, if you need.

Viewpager not saving Fragment states

First of all I would like to thank the stackoverflow community. Thanks to you I solved so much problems! Usually I bang my head over the wall for hours and I find the solution here (98% percent of the time). This time I would like to share my problem.
This is the first app I'm developing. I have one activity (is this bad?). My app structure is the following: Nav drawer which contains four items - two viewpagers and two static fragments. The viewpagers contains lists with data and if you click on one of the items from the list you are present with a detail page which again is a viewpager. When you are on the detail page you can click and advance to other fragment. The problem is that when I advance to the other fragment onSavedInstance is not called for the viewpagerdetails and I can't retain the fragment state. onSavedInstance will be called if I pass to the FragmentPagerAdapter getFragmentManager(), instead of getChildFragmentManager(), but if I do this when I navigate back, the viewpager items are blank. I have tried using FragmentStatePagerAdapter, but when I click back from the 'other fragment' to return to viewpager details the app crashes with the following error: Fragment no longer exists for key f0: index 0. I have looked over the internet, but I didn't found a working solution. Some say that the problem is from the adapter, but I tried this solution and it didn't work. Also I want to manually retain my fragment state, please don't offer me the fix with the configchanges in the app manifest. I have tried to call onSavedInstanceState from the onStop method, but when I return to the fragment the saved state is empty. Should I implement this with a static variable in my mainActivity?
FragmentPagerAdapter:
public class DetailsSlideAdapter extends FragmentPagerAdapter {
private String[] navMenuTitles;
private FragmentManager manager;
private FragmentTransaction mCurTransaction = null;
private Resources res;
public DetailsSlideAdapter(FragmentManager fm, Resources res) {
super(fm);
this.manager = fm;
navMenuTitles = res.getStringArray(R.array.detailTabs);
this.res = res;
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
DetailsInfo info = new DetailsInfo();
return info;
case 1:
DetailsCast cast = new DetailsCast();
return cast;
case 2:
DetailsOverview overview = new DetailsOverview();
return overview;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return navMenuTitles[0];
case 1:
return navMenuTitles[1];
case 2:
return navMenuTitles[2];
default:
return navMenuTitles[1];
}
}
Viewpager details:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Get the ViewPager and set it's PagerAdapter so that it can display items
DetailsSlideAdapter = new DetailsSlideAdapter(getChildFragmentManager(), getResources());
mViewPager = (ViewPager) rootView.findViewById(R.id.DetailsPager);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(DetailsSlideAdapter);
// Give the SlidingTabLayout the ViewPager, this must be done AFTER the ViewPager has had
// it's PagerAdapter set.
mSlidingTabLayout = (DetailsSlidingTabLayout) rootView.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setViewPager(mViewPager);
mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.tabSelected));
}
If other code is needed I will post it. Thanks.
EDIT using FragmentStateAdapter:
App crashes: Fragment no longer exists for key f0: index 0. On the internet people say that the problem is from the adapter, but I tried this solution and it didn't work. Code:
public class DetailsSlideAdapter extends FragmentStatePagerAdapter {
private String[] navMenuTitles;
private FragmentManager manager;
private FragmentTransaction mCurTransaction = null;
private Resources res;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public DetailsSlideAdapter(FragmentManager fm, Resources res) {
super(fm);
this.manager = fm;
navMenuTitles = res.getStringArray(R.array.detailTabs);
this.res = res;
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
DetailsInfo info = new DetailsInfo();
return info;
case 1:
DetailsCast cast = new DetailsCast();
return cast;
case 2:
DetailsOverview overview = new DetailsOverview();
return overview;
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return navMenuTitles[0];
case 1:
return navMenuTitles[1];
case 2:
return navMenuTitles[2];
default:
return navMenuTitles[1];
}
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
Have you seen this? FragmentStatePagerAdapter
From the Docs:
Implementation of PagerAdapter that uses a Fragment to manage each
page. This class also handles saving and restoring of fragment's
state.

Android ViewPager Bug on Swipe

I have this weird issue with the viewPager. When I swipe from one fragment to the next and then swipe back, the layout is correct, but when pressing an element (Listview item for example), the previous java code still did not update with the view. I don't know if I can explain this any better, as it works when I play with the swipe until the fragment works like its supposed to. here is my code:
Main.Java:
public class Main extends FragmentActivity {
SectionsPagerAdapter mAdapter;
ViewPager mViewPager;
// for alert transitions
AlertDialog dialog;
// share button
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// set up button
getActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAdapter);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
}
#Override
public void onBackPressed() {
if (mViewPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
}
}
}
SectionsPagerAdapter.java:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new Important();
case 1:
return new Propositions();
case 2:
return new Information();
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return ("Important Dates").toUpperCase(l);
case 1:
return ("Props").toUpperCase(l);
case 2:
return ("Information").toUpperCase(l);
}
return null;
}
}
The Fragments all use the onCreateView() method.
Thanks in advance for your help!
Maybe a late response, but I've experienced the same issue.
The problem was the DepthPageTransformer you are using from the Android Developers example for PageTransformer.
There is a bug with stacking fragments and layer priority, I assume. By fixing the custom PageTransformer will fix your "swipe back" issue. Or if you don't mind the animation, just remove your custom PageTransformer and use the default animation (by adding nothing).

Categories