Android FragmentActivity/FragmentPagerAdapter and actionBar update onCreateOptionsMenu - android

I have an activity that uses a fragmentpageradapter to create an ics style actionBar. Each page needs to update the actionBar though. Is there a way I can call onCreateOptionsMenu in my onPageSelected?
I've trimmed a lot of the code out from the example below for simplicity's sake.
public class ListFragmentViewPagerActivity extends FragmentActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread_view);
ViewPager pager = (ViewPager) findViewById(android.R.id.list);
pager.setAdapter(new ExamplePagerAdapter(getSupportFragmentManager()));
TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(pager);
indicator.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
});
}
public class ExamplePagerAdapter extends FragmentPagerAdapter implements TitleProvider{
public ExamplePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return URLS.size();
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new ThreadFragment();
// set arguments here, if required
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public String getTitle(int pos) {
return TITLES.get(pos);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = new MenuInflater(this);
menuinflate.inflate(R.menu.thread_menu, menu);
if (type.equals("xda")) {
menu.removeItem(R.id.ss_view);
}
//This worked when I only needed to call it one time. I need to update this menu for each page in my viewPager though.
if (isFav) {
menu.getItem(2).setIcon(R.drawable.fav_ab);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.ss_view:
Intent ssi = new Intent(this, SSActivity.class);
ssi.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle b = new Bundle();
ssi.putExtras(b);
startActivity(ssi);
break;
case R.id.restart:
break;
case R.id.fav_ab:
break;
default:
return super.onOptionsItemSelected(item);
}
return false;
}
}
UPDATE
Calling invalidateOptionsMenu() in my onPageSelected() did the trick!

Use invalidateOptionsMenu() but make sure you wrap this in a trycatch if you are supporting anythign below 3.0, as this method does not exist and will crash!
If you want to update your menu on pre 3.0 devices, override the onPrepareOptionsMenu() as well, which will be called everytime the menu is opened.

Related

When back button is pressed the APP exit. Why?

In my App when i press back button from the following activity doesn't return to main activity(fragment) but the App close.
public class ListaSmartphone extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_smartphone);
Button buttonSP = (Button)findViewById(R.id.buttonXIAOMI);
buttonSP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openListaSP = new Intent(ListaSmartphone.this, ElencoXiaomi.class);
startActivity(openListaSP);
}
});
Button buttonTB = (Button)findViewById(R.id.buttonMEIZU);
buttonTB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openListaTB = new Intent(ListaSmartphone.this, ElencoMeizu.class);
startActivity(openListaTB);
}
});
}
}
THIS IS THE MAIN ACTIVITY CODE
public class MainActivity extends AppCompatActivity {
FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
vpPager.setPageTransformer(true, new RotateUpTransformer());
}
#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_main, menu);
return true;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static final String[] TAB_TITLES = new String[]{"WOW STORE", "PRODOTTI", "SERVIZI", "INFO"};
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentWithZeroImage.newInstance("", R.drawable.wowstorelogo);
case 1:
return FragmentWithOneImage.newInstance("", R.drawable.prodotti);
case 2:
return FragmentWithTwoImages.newInstance("", R.drawable.riparazioni);
case 3:
return FragmentWithThreeImages.newInstance("", R.drawable.info);
default:
return null;
}
}
#Override
public int getCount(){
return TAB_TITLES.length;
}
#Override
public CharSequence getPageTitle(int position){
return TAB_TITLES[position];
}
}
}
The Application works fine, no error but on a devices whe back button is pressed the App exits and doesn't back to MainActivity.
I use Main Activity with four fragments.
While Passing Intent you might have used finish(); after startActivity()
use this code :
#Override
public void onBackPressed() {
this.startActivity(new Intent(ListaSmartphone.this,MainActivity.class));
// super.onBackPressed();
}
and open the fragment in onCreate function of MainActivity
If you want to go back to the MainActivity on back button press then use this code
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}

How to add back button on action bar with more tabs

know anyone how can I add one back button on my action bar? I want to add the back button befor INFO tab. I've try some method but no one of them don't work for me. Well let's start with started.
In this image in left part it's what I need to do as actionbar and in the right part it's how looks my project right now.
I've try to put that code for add the back button but it don't works:
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
Here it's my Activity:
public class TrailActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Intent intent;
Trail trail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
setContentView(R.layout.trail_fracment_main);
trail = intent.getParcelableExtra("trail");
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
InfoFragments infoFragments = new InfoFragments();
infoFragments.setTrail(trail);
Fragment fragment = infoFragments;
return fragment;
} else if (position == 1) {
return new MapFragments();
} else {
return new WondersFragments();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
Some one told me to try to implement OnBackStackChangedListener and after that he want to put in my code and that:
#Override
public void onCreate(Bundle savedInstanceState) {
//Listen for changes in the back stack
getSupportFragmentManager().addOnBackStackChangedListener(this);
//Handle when activity is recreated like on orientation Change
shouldDisplayHomeUp();
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
getSupportFragmentManager().popBackStack();
return true;
}
Also I've try to add and that override method, but again... nothing happen :(
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I've try and that... but again... I've don't obtain any result :(.
So please guys, if anyone know how can I solve that problem, please show me.. I really need to do that and how much fast is possible.

How to swipe between Fragments with FragmentPagerAdapter

I can't figure out why swiping between my Fragments isn't working,
Here is my custom FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new PrearrivalPlan();
case 1:
return new PrimarySurvey();
case 2:
return new Vitals();
case 3:
return new SecondarySurvey();
case 4:
return new PrepareForTravel();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 5;
}
}
And here is my activity that uses it:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private CustomViewPager viewPager;
private TabsPagerAdapter tabsPagerAdapter;
private ActionBar actionBar;
private String[] tabTitles = {"Pre-arrival Plan", "Primary Survey", "Vitals", "Secondary Survey", "Prepare for Travel"};
private int totalTabs = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (CustomViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
tabsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(tabsPagerAdapter);
viewPager.setPagingEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
viewPager.setOffscreenPageLimit(totalTabs);
// Remove Android icon from Action Bar
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowHomeEnabled(false);
// Add tabs to Action Bar
for (String tab_name : tabTitles) {
SpannableString s = new SpannableString(tab_name);
s.setSpan(new TypefaceSpan("helveticaneuelight.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
actionBar.addTab(actionBar.newTab().setText(s).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void updateTabTitles(int tabNumber, int checkBoxesRemaining) {
String text = tabTitles[tabNumber] + "\n (" + checkBoxesRemaining + " unchecked)";
actionBar.getTabAt(tabNumber).setText(text);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
return true;
case R.id.complete:
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
goToReport();
break;
case DialogInterface.BUTTON_NEGATIVE:
// "No" button clicked, do nothing
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to complete the checklist?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToReport() {
Intent intent = new Intent(this, Report.class);
startActivity(intent);
}
};
could it be this viewPager.setPagingEnabled(false); method? Try taking that method out, or at least setting it to true.

FragmentPagerAdapter getItem() is returning more than it should

I have a MainActivity that controls four fragments, each of which is a tab. When my main activity starts, I have a line being printed to the log to show me what fragment is being instantiated. Here is my FragmentPagerAdapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
System.out.println("Returning new PrearrivalPlan()");
return new PrearrivalPlan();
case 1:
System.out.println("Returning new PrimarySurvey()");
return new PrimarySurvey();
case 2:
System.out.println("Returning new SecondarySurvey()");
return new SecondarySurvey();
case 3:
System.out.println("Returning new PrepareForTravel()");
return new PrepareForTravel();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
The tab bar has the following options in order:
Prearrival Plan | Primary Survey | Secondary Survey | Prepare for Travel
When my main activity starts, the following is printed to the screen:
Returning new PrearrivalPlan()
Returning new PrimarySurvey()
What it seems to be doing is loading one tab ahead of the one I have selected. Since PrearrivalPlan is the first tab, I would think it should just return a new PrearrivalPlan() except it returns both. Another example, when I click on Primary Survey tab (second tab), the following is printed to the screen:
Returning new SecondarySurvey() // <- This is the third tab!?
Because PrimarySurvey was already instantiated when the activity first started (see output above), it jumped ahead just like it did before and loaded the third tab even though I only clicked on the second.
Here is my MainActivity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private CustomViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
private String[] tabTitles = {"Pre-arrival Plan", "Primary Survey", "Secondary Survey", "Prepare for Travel"};
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (CustomViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
viewPager.setPagingEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager.setOnPageChangeListener(new CustomViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// Remove Android icon from Action Bar
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
getActionBar().setDisplayShowHomeEnabled(false);
// Add tabs to Action Bar
for (String tab_name : tabTitles) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void updateTabTitles(int tabNumber, int checkBoxesRemaining) {
String text = tabTitles[tabNumber] + " \n (" + checkBoxesRemaining + ")";
actionBar.getTabAt(tabNumber).setText(text);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
return true;
case R.id.complete:
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
goToReport();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to complete the checklist?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToReport() {
Intent intent = new Intent(this, Report.class);
startActivity(intent);
}
It is the expected behaviour of ViewPager. ViewPager always keeps one tab ahead and behind in memory in order to show slider animation. If you don't you have the next or previous tab (or fragment) in memory, trying to initiate the fragment during the slider transition will cause a performance lag or at the worse you will have the sliding fragment to be empty and get loaded later.
ViewPager also allows you to set page offset limit through setOffscreenPageLimit() which will control amount fragment to keep them in memory. By default, this is 1 which means one fragment ahead and behind will always be there in memory

Using backstack and back button in viewpager

I'm using a viewpager to swipe between fragments and would like the back button to navigate to the previously viewed fragment rather than ending the activity. Sorry if this is a duplicate of this question however I didn't find the answer very helpful. Obviously onBackPressed needs to be overridden, but I don't know how to get and display the correct fragment. I assume that I should use the fragmentmanager's backstack, but getSupportFragmentManager().getBackStackEntryCount() always returns 0. Do I need to manually add fragments to the backstack using FragmentTransaction.addToBackStack()? If so, where would I add this in my adapter?
Here is the code for my activity,
public class PagerActivity extends FragmentActivity {
ArrayList<Sale> sales;
MyAdapter mAdapter;
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent it = getIntent();
this.sales = (ArrayList<Sale>) it.getExtras().get("sales");
int position = it.getExtras().getInt("position");
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(position);
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public int getCount() {
return sales.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
#Override
public Fragment getItem(int position) {
SalesThumbFragment frag = new SalesThumbFragment();
return frag.newInstance(sales.get(position));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sales_controller, menu);
return true;
}
#Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount() != 0) {
getSupportFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
In new design support library, i use this
I have same issue and i follow this step
In the main activity where there are 3 fragment in viewpager i create stack
and push and pop data.
//private Stack<Integer> stackkk; ==> As i get edit suggestion
private Stack<Integer> stackkk = new Stack<>(); // Edited
private ViewPager mPager;
private int tabPosition = 0;
mTabLayout.setupWithViewPager(mPager);
mPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tabPosition = tab.getPosition();
mPager.setCurrentItem(tab.getPosition());
if (stackkk.empty())
stackkk.push(0);
if (stackkk.contains(tabPosition)) {
stackkk.remove(stackkk.indexOf(tabPosition));
stackkk.push(tabPosition);
} else {
stackkk.push(tabPosition);
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tabPositionUnselected = tab.getPosition();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
and in the onBackPressed in activity,
#Override
public void onBackPressed() {
if (stackkk.size() > 1) {
stackkk.pop();
mPager.setCurrentItem(stackkk.lastElement());
} else {
}
}
Use this code in Fragment Activity class. Don't forget to add return true;
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
mViewPager.setCurrentItem(viewPageSelected - 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
I had a similar problem, this is how I solved it. I think you can adapt the code to your problem, if I understood what you problem is. I had a ViewPager with 6 fragments and wanted to keep track of the page history and to be able to use the back button to navigate backwards in the history. I create a java.util.Stack<Integer> object, add fragment numbers to it (except when you use the back button, see below), and override onBackPressed() to make it pop the last viewed fragment instead of using the back stack, when my history stack is not empty.
You want to avoid pushing elements on the Stack when you press the back button, otherwise you will get stuck between two fragments if you keep using the back button, instead of eventually exiting.
My code:
MyAdapter mAdapter;
ViewPager mPager;
Stack<Integer> pageHistory;
int currentPage;
boolean saveToHistory;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.container);
mPager.setAdapter(mAdapter);
mPager.setOffscreenPageLimit(5);
pageHistory = new Stack<Integer>();
mPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
if(saveToHistory)
pageHistory.push(Integer.valueOf(currentPage));
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
saveToHistory = true;
}
#Override
public void onBackPressed() {
if(pageHistory.empty())
super.onBackPressed();
else {
saveToHistory = false;
mPager.setCurrentItem(pageHistory.pop().intValue());
saveToHistory = true;
}
};
If you use a field to keep track of the index of the previous page using mPager.getCurrentItem() after each time the user navigates to a new fragment, then in the onBackPressed() method, you should be able to call mPager.setCurrentItem(previousPage)
Or, if the user can only page in order, then you don't need a field at all, and you could just do mPager.setCurrentItem(mPager.getCurrentItem()-1)
I've made custom ViewPager and implement stack functionality in it.
public class CustomViewPager extends ViewPager {
private Stack<Integer> stack = new Stack<>();
#Override
public void setCurrentItem(int item, boolean smoothScroll) {
stack.push(getCurrentItem());
super.setCurrentItem(item, smoothScroll);
}
public int popFromBackStack(boolean smoothScroll) {
if (stack.size()>0) {
super.setCurrentItem(stack.pop(), smoothScroll);
return getCurrentItem();
} else return -1;
}

Categories

Resources