I get the next error: java.lang.IllegalStateException: Fragment already added.
This is a layout getting inflated each time I change tab, as seen in this photo:
![FirstTab]http://prntscr.com/h4e8pc
![SecondTab]http://prntscr.com/h4ebyn
So i get the idea of the problem, but I've tried many ways to fix it with no result. I've tried to use .replace instead of .add, that way it doesnt crash but the map is not loaded. And also tried to delete the fragment as soon as I switch to that tab but the result is similar to the .replace one.
case R.id.navigation_dashboard:
frame = (FrameLayout) findViewById(R.id.content);
frame.removeAllViewsInLayout();
LayoutInflater.from(getApplicationContext())
.inflate(R.layout.activity_prueba_dashboard, frame, true);
fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content2, mMapFragment);
fragmentTransaction.commit();
mMapFragment.getMapAsync(my_maps_class);
I believe it's much cleaner to use viewpager in that situation. Check this code :
public class HomeViewPagerAdapter extends FragmentPagerAdapter {
public static final int FRAGMENT_A_INDEX = 0;
public static final int FRAGMENT_B_INDEX = 1;
public static final int FRAGMENT_C_INDEX = 2;
public static final int FRAGMENTS_COUNT = 3;
public HomeViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case FRAGMENT_A_INDEX:
return FragmentA.newInstance();
case FRAGMENT_B_INDEX:
return FragmentB.newInstance();
case FRAGMENT_C_INDEX:
return FragmentC.newInstance();
default:
return null;
}
}
#Override
public int getCount() {
return FRAGMENTS_COUNT;
}
}
and then link the adapter with the ViewPager in the hosting appcompat activity as here :
HomeViewPagerAdapter homeTabsAdapter = new HomeViewPagerAdapter(getSupportFragmentManager());
homeTabsViewPager.setAdapter(homeTabsAdapter);
and you can easily switch between fragments by calling :
homeTabsViewPager.setCurrentItem(HomeViewPagerAdapter.FRAGMENT_A_INDEX, false);
You seen to be trying replacing the content of the same Fragment, in this case you dont need the FragmentTransaction.
The solution is to create a second fragment on which you have the map, in this case the Transaction is needed.
Related
I have trouble finding a good example on how to swipe between fragments with help of bottom navigatiom bar. Since FragmentStatePagerAdapter is deprecated and a new ViewPager2 is now recommended instead of the old ViewPager I want to use ViewPager2 and FragmentStateAdapter in my code instead. I have found an example of how to combine BottomNavigationBar and ViewPager here and I want to do something similar. My code have many similarities to the one in the example with the only difference that I have my code in a fragment instead of an activity. Here is a picture of how my FrontendFragment display look like. I can switch between the views using the bottomnavigationbar but I also want to be able to swipe between the views. Can someone help me or at least direct me on the right way? Here is my code:
FragmentPagerAdapter Class:
public class FragmentPagerAdapter extends FragmentStateAdapter {
private static final int mFragmentCount = 5;
public FragmentPagerAdapter(#NonNull Fragment fragment) {
super(fragment);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position){
case 0:
return new HomeFragment();
case 1:
return new SearchFragment();
case 2:
return new AddFragment();
case 3:
return new MessageFragment();
case 4:
return new ProfileFragment();
}
return null;
}
#Override
public int getItemCount() {
return mFragmentCount;
}
}
FrontendFragment Class:
public class FrontendFragment extends Fragment implements BottomNavigationView.OnNavigationItemSelectedListener{
private BottomNavigationView mBottomNavigationView;
private ViewPager2 mViewPager2;
private FragmentPagerAdapter mFragmentPagerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_frontend, container, false);
loadFragment(new HomeFragment());
mBottomNavigationView = v.findViewById(R.id.bottomNavigationBar);
mBottomNavigationView.setOnNavigationItemSelectedListener(this);
return v;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home_icon:
selectedFragment = new HomeFragment();
break;
case R.id.search_icon:
selectedFragment = new SearchFragment();
break;
case R.id.add_icon:
selectedFragment = new AddFragment();
break;
case R.id.message_icon:
selectedFragment = new MessageFragment();
break;
case R.id.profile_icon:
selectedFragment = new ProfileFragment();
break;
}
return loadFragment(selectedFragment);
}
private boolean loadFragment(Fragment selectedFragment) {
if(selectedFragment != null){
MainActivity.sFm.beginTransaction().replace(R.id.relLayoutMiddle, selectedFragment).commit();
return true;
}
return false;
}
}
Thanks in advance!
As I'm already using BottomNav with ViewPager2 in one of my app, I can help.
Your code is partially correct which means your FragmentPagerAdapter is fine, but not your FrontEndFragment.
See, the FragmentPagerAdapter has to be set to a ViewPager2 as
//this here is the FrontEndFragment
mViewPager2.setAdapter(new FragmentPagerAdapter(this));
Then, You don't have to do the FragmentTransaction at all, you just have to change the ViewPager2's current item position through the BottomNavigationBar as
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home_icon:
mViewPager2.setCurrentItem(0);
break;
case R.id.search_icon:
mViewPager2.setCurrentItem(1);
break;
case R.id.add_icon:
mViewPager2.setCurrentItem(2);
break;
case R.id.message_icon:
mViewPager2.setCurrentItem(3);
break;
case R.id.profile_icon:
mViewPager2.setCurrentItem(4);
break;
}
return false;
}
This is all, you don't have to deal with Fragments at all apart from the FragmentPagerAdapter. Also, don't forget to remove the loadFragment(new HomeFragment()); which is not required, nor the function loadFragment() is required.
(Optional), Furthermore, if you want to disable the Swipe Action of the ViewPager2 and want the Fragments to be selected based on the Selected BottomNav item only, then you can set setUserInputEnabled() property of ViewPager2 as false.
Next, to set the BottomNavigationBar's item as selected based on the swipe of the ViewPager2, what you've to do is,
Create a global var
MenuItem previousMenuItem;
Then, set a default item (first) to be selected of BottomNav on activity start as
mBottomNavigationView.getMenu().getItem(0).setChecked(true);
Finally, set an OnPageSelected() callback on ViewPager2 to update the selected Menu Item as:
mViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
if (previousMenuItem != null) {
previousMenuItem.setChecked(false);
}
else {
mBottomNavigationView.getMenu().getItem(0).setChecked(false);
}
mBottomNavigationView.getMenu().getItem(position).setChecked(true);
previousMenuItem = mBottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
super.onPageScrollStateChanged(state);
}
});
What you're doing here is that you're setting default item to previousMenuItem and then on swiping to a different page, deselecting the previousMenuItem and selecting the new one, which means updating the BottomNav based on ViewPager's current item. This is the complete code you require to acheive your objective.
If you want to swipe between views, a simple solution would be to store all views in your parent view, but set all layouts for views except the initial view to android:visibility="gone". Make sure to set the initial view layout to android:visibility="visible" though. Now on you button clicks, you will have to implement onClick such that they turn on/ off view visibilities accordingly. For example, store views in order and control them via array index. But the whole thing you're trying to do is generally not a good design pattern in my opinion.
Why don't you load another Activity onClick instead of crowding your single activity? This will cause load time issues. Even if the views are non-visible, it's just an overall hassle to maintain all that in one place.
Background
I have an android app using fragments. I'm using a separate FragmentPagerAdapter (i.e. as a separate class, outside MainActivity).
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(mViewPager);
}
SectionsPagerAdapter.java
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new frag1();
case 1:
return new frag2();
case 2:
return new frag3();
case 3:
return new frag4();
case 4:
return new frag5();
default:
return null;
}
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Name1";
case 1:
return "Name2";
case 2:
return "Name3";
case 3:
return "Name4";
case 4:
return "Name5";
}
return null;
}
The Issue
I need to refresh the view of, say, fragment #3 from fragment#2 (the ultimate goal is for changes the user initiates on fragment #2 to be visible as soon as the user proceeds to fragment#3. I have tried to detach/attach fragment #3 itself as soon as it is visible, like this:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
Unfortunately, a) this has a penalty in performance, as there is a "stutter" during navigation; b) it doesn't work reliably. Some things (the texts of some buttons) are not refreshed, for some reason I can't figure out.
In any case, I have discovered that the only 100% reliable method for forcing a refresh/redraw is to restart the activity (for example through an onClickListener on a Save button the user needs to press on the previous fragment, #2). But this restarts the Activity on fragment #1
My Question
How can I restart the activity on this specific fragment (#3), considering the fact I'm using a separate FragmentPagerAdapter?
I've studied several other questions/answers, for example this: https://stackoverflow.com/a/36064344
but how can I implement something like this (putting extras on the intent call) when the FragmentPagerAdapter is on a separate class? Alternatively, is there something else I can do to refresh the fragment view?
If you need extra info or code, let me know and I'd be glad to add clarification.
EDIT:
I managed to find another solution that so far seems to be working as intended. I added the following code on the onClickListener of the Save button on fragment #2
frag3 f3 = new frag3();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragmentContainer, f3);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
However, I'm still interested in my original question (how to start an activity on a specific fragment when using a separate FragmentPagerAdapter), so if you have any ideas about that, I'm all ears.
Well, wasn't that simple...
this.recreate(); not only restarts the activity but it also remembers the fragment position.
Just in case someone else needs this, when you're working from fragments you need to use it this way:
First declare the activity which contains the fragment in question. E.g.
public class frag1 extends Fragment {
...
Activity mactivity;
#Override
public void onAttach(Activity MainActivity) {
super.onAttach(MainActivity);
mactivity = MainActivity;
}
Then instead of getActivity().recreate(); simply use mactivity.recreate();
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.
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.
I'd like to be able to not allow switching to one of my 3 fragments in my custom FragmentPagerAdapter when certain conditions are met. Unfortunately I failed to find any help.
I'd prefer to not remove and re-add the fragment (item 0), as this criterium can change inside the FragmentActivity any time and I'd need the fragment to be able to receive and handle messages.
Any suggestions? Please ask if something's unclear.
Edit: Sharing some code
Main activity:
#Override
protected void onResume() {
super.onResume();
...
_sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), this, cardnumber, pin);
_viewPager = (ViewPager) findViewById(R.id.pager);
_viewPager.setAdapter(_sectionsPagerAdapter);
_viewPager.setOnPageChangeListener(_sectionsPagerAdapter);
_viewPager.setCurrentItem(1);
_viewPager.setOffscreenPageLimit(2);
This seems a bit rude, but it works
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
Bundle args = new Bundle();
switch (position) {
case CUSTOMER_DETAILS_PAGE:
// fragment = _fragments.get(TRLIST_PAGE);
fragment = new UserDetailFragment();
args.putString("TAG", "details");
break;
case BALANCE_PAGE:
// fragment = _fragments.get(BALANCE_PAGE);
fragment = new BalanceFragment();
args.putString("TAG", "balance");
break;
case TRLIST_PAGE:
// fragment = _fragments.get(TRLIST_PAGE);
fragment = new TrListFragment();
args.putString("TAG", "trlist");
break;
default:
break;
}
_listeners.put(position, (MyTabSelectedListener) fragment);
// fragment = (Fragment) _listeners.get(position);
args.putString("cardnumber", _cardnumber);
args.putString("pin", _pin);
fragment.setArguments(args);
return fragment;
}
I want to limit access to the CUSTOMER_DETAILS_PAGE when it would be empty anyway.
After reading corsair992-s answer here https://stackoverflow.com/a/23967701/3153792 and looking at the CWAC-Pager source code here https://github.com/commonsguy/cwac-pager I managed to find what I was looking for.
The key was to change the getItemPosition function (which I didn't even use before) to get the TAG argument (set in getItem) from the fragments and identify them that way:
#Override
public int getItemPosition(Object item) {
Fragment fragment = (Fragment) item;
String title = fragment.getArguments().getString("TAG");
int position = tabs.indexOf(title);
if (position >= 0) {
return position;
} else {
return POSITION_NONE;
}
First I define tags for each tab and a list to hold them in order of appearance:
public static final String CUSTOMER_DETAILS_PAGE = "detail";
public static final String BALANCE_PAGE = "balance";
public static final String TRLIST_PAGE = "trlist";
List<String> tabs = new ArrayList<String>();
Afterwards, I add them in the constructor in the original order:
tabs.add(CUSTOMER_DETAILS_PAGE);
tabs.add(BALANCE_PAGE);
tabs.add(TRLIST_PAGE);
When I need to hide a tab, I just remove it from the list and notify the adapter:
public void disableUserDetail() {
tabs.remove(tabs.indexOf(CUSTOMER_DETAILS_PAGE));
notifyDataSetChanged();
}
My fragment specifically goes to the left side (the beginning) but it would be easy to change:
public void enableUserDetail() {
tabs.add(0, CUSTOMER_DETAILS_PAGE);
notifyDataSetChanged();
}
I had to change getItem and getPageTitle to use the tabs list and TAG constants as identifier (which I also include as arguments for getItemPosition):
#Override
public Fragment getItem(int position) {
String id = tabs.get(position);
Fragment fragment = null;
Bundle args = new Bundle();
if (id.equals(CUSTOMER_DETAILS_PAGE)) {
fragment = new UserDetailFragment();
args.putString("TAG", CUSTOMER_DETAILS_PAGE);
...
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
String id = tabs.get(position);
if (id.equals(CUSTOMER_DETAILS_PAGE)) {
return _ctx.getString(R.string.title_section1).toUpperCase(l);
...