Disable fragment reload data in viewpager - android

I am using ViewPager in my Android project, and I use FragmentStatePagerAdapter to set the pages.
class MyPageAdapter extends FragmentStatePagerAdapter {
List<Fragment> mList = new ArrayList<>();
public MyPageAdapter(FragmentManager fm) {
super(fm);
this.init();
}
private void init() {
mList.add(new FragmentOne());
mList.add(new FragmentTwo());
mList.add(new FragmentThree());
....
}
#Override
public Fragment getItem(int position) {
return mList.get(position);
}
}
And for each Fragment data will be loaded from the server once the view created, like this:
public class FragmentOne extends Fragment {
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(getViewResourceId(), container, false);
ButterKnife.bind(this, v);
setRetainInstance(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
mRecycleView.setLayotManager(linearLayoutManager);
endlessRecyclerViewScrollListener = new EndlessRecyclerViewScrollListener((LinearLayoutManager) mRecycleView.getLayoutManager()) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
loadByPage(page);
}
};
mRecycleView.addOnScrollListener(endlessRecyclerViewScrollListener);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAdapter = createAdapter();
mRecycleView.setAdapter(mAdapter);
loadByPage(1); // load data from server
}
}
As shown, the Fragment contains a endless recyclerview.
So far so good. However once I change the selected view pageļ¼Œ I found that the data will be reloaded every time. For example, I have scroll 3 pages in FragmentOne, and then change to FragmentTwo, and when I change to FragmentOne back, FragmentOne will try load data of page 1.
Is it possible to avoid this?

you can do something like this :
private boolean isDataCalled = true;
private List<ItemModel> itemModelList;
and then
if (isDataCalled){
loadByPage(1); // Initialize itemModelList in this method
setItemAdapter(itemModelList);
isDataCalled = false;
}else {
setItemAdapter(itemModelList);
}
setItemAdapter method
private void setItemAdapter(List<ItemModel> itemModelList){
mAdapter = createAdapter(itemModelList);
mRecycleView.setAdapter(mAdapter);
}

Related

Android TabLayout with ViewPager duplicates fragment contents when rotating

My app has a tablayout with a view pager. Each page has a fragment. There are 4 different fragments, three of them are basically the same for now (I'm in the development phase right now). One of them has a RecyclerView with a basic list.
I am implementing the Two-pane template in the fragment with the RecyclerView.
Everything seems to be works]ing well. While I move across the tabs the fragments are loaded fine.
But, when I rotate the device and tap on the first tab, and then go back to the one with the recyclerview, I can see the previous intance below. See attached images.
I decided to use static final instances of the fragments in the page adapter and in the recyclerview fragment.
How can I get rid of this problem?
Thanks in advance stackers!
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon1).setText(R.string.dashboard));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon2).setText(R.string.fragment2));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon3).setText(R.string.fragmentDualPane));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.icon4).setText(R.string.frag4));
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter pageAdapter = new TabPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pageAdapter);
tabLayout.setupWithViewPager(viewPager);
} // protected void onCreate
} // public class MainActivity
TabPagerAdapter has static final intances of the fragments
public class TabPagerAdapter extends FragmentPagerAdapter {
static final Fragment tabs[] = {new DashboardFragment(),
new Fragment2(),
new ExpensesFragment(),
new Fragment4()
};
public TabPagerAdapter(#NonNull FragmentManager fm) {
super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
} // public TabPagerAdapter
#NonNull
#Override
public Fragment getItem(int position) {
if (position<tabs.length)
return tabs[position];
else
return null;
} // public Fragment getItem
#Override
public int getCount() {
return this.tabs.length;
} // public int getCount
} // class TabPagerAdapter
General fragment template for dashboard, fragment2, and fragment4
public class DashboardFragment extends Fragment {
public DashboardFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} // onCreate
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_dashboard, container, false);
}
}
This is the code for the fragment with the dual pane. Look that it uses the OnItemSelected implementation of fragments communications.
This fragment loads another fragment with the recyclerview.
public class ExpensesFragment extends Fragment
implements IOnItemSelected {
#Override
public void onAccountSelected(Account item) {
System.out.println("Clicking on " + item.getTitle() + ", and isTwoPane=" + isTwoPane);
} // public void onAccountSelected
public static final String TAG="Expenses Fragment";
private boolean isTwoPane = false; // Let's assume we're on a phone
private FragmentManager fragmentManager;
private View fragmentView = null;
public ExpensesFragment() {
// Required empty public constructor
} // ExpensesFragment()
public static final ExpensesListFragment lListFragment = new ExpensesListFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} // onCreate
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentView = inflater.inflate(R.layout.fragment_expenses, container, false);
isTwoPane = fragmentView.findViewById(R.id.expensesDetailContainer) != null;
fragmentManager = getChildFragmentManager();
if (savedInstanceState==null) {
if ( !lListFragment.isAdded() ) {
fragmentManager.
beginTransaction().
add(R.id.expensesListContainer,lListFragment).
commit();
} // if ( !lListFragment.isAdded() )
} // if (savedInstanceState==null)
if ( isTwoPane ) {
fragmentManager.
beginTransaction().
replace(R.id.expensesDetailContainer,new EmptyFragment()).
commit();
} // if ( isTwoPane )
return fragmentView;
} // onCreateView
} // ExpensesFragment
And this is the fragment with the recyclerview:
public class ExpensesListFragment extends Fragment {
private IOnItemSelected mCallback;
private RecyclerView rv;
private RecyclerView.LayoutManager rvlm;
private RecyclerAdapterAccounts rva;
public ExpensesListFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCallback = (IOnItemSelected)getParentFragment();
} // onCreate
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_expenses_list, container, false);
if ( isVisible() ) return fragmentView;
FragmentManager fragmentManager = getChildFragmentManager();
// Setting the recyclerview environment
rv = fragmentView.findViewById(R.id.expensesRV); // recycler view
rvlm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(rvlm);
rva = new RecyclerAdapterAccounts();
rva.setCallBackFunction(mCallback);
rv.setAdapter(rva);
// Setting the floating action button and snackbar
FloatingActionButton fab = fragmentView.findViewById(R.id.fabAdd);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Load a Create Item frag", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
return fragmentView;
} // onCreateView
} // public class ExpensesListFragment
The RecyclerAdapterAccounts creates a generic set of data:
public class RecyclerAdapterAccounts extends
RecyclerView.Adapter<RecyclerAdapterAccounts.ViewHolderAccounts> {
private IOnItemSelected callBackFunction;
public IOnItemSelected getCallBackFunction() {return callBackFunction;}
public void setCallBackFunction(IOnItemSelected callBackFunction) {this.callBackFunction = callBackFunction;}
class ViewHolderAccounts extends RecyclerView.ViewHolder {
ImageView icon, isRepeating, isAlert;
TextView title, total;
public Account getAccount() {return account;}
public void setAccount(Account account) {this.account = account;}
Account account;
public ViewHolderAccounts(View itemView) {
super(itemView);
icon = itemView.findViewById(R.id.list_item_ico_account);
isRepeating = itemView.findViewById(R.id.list_item_isrepeating);
isAlert = itemView.findViewById(R.id.list_item_isalert);
title = itemView.findViewById(R.id.list_item_title_account);
total = itemView.findViewById(R.id.list_item_desc_account);
account = null; // The account needs to be set using the setter/getter method
} // ViewHolderAccounts
} // class ViewHolderAccounts
List<Account> accts = new ArrayList<Account>();
ViewGroup parent;
#NonNull
#Override
public ViewHolderAccounts onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_account,parent,false);
this.parent = parent;
ViewHolderAccounts vh = new ViewHolderAccounts(v);
return vh;
} // onCreateViewHolder
#Override
public void onBindViewHolder(#NonNull ViewHolderAccounts holder, int position) {
// Look into the list the item with id=position
Optional<Account> la = accts.stream()
.filter(ac->ac.getId()==(long)position)
.findFirst();
if ( la.isPresent() ) {
int res = parent.getResources().getIdentifier(la.get().getIcon(), "drawable", "com.almonisolutions.elgddt");
holder.icon.setImageResource(res);
holder.isRepeating.setImageResource(R.drawable.automatic);
holder.isAlert.setImageResource(R.drawable.notifications);
holder.title.setText(la.get().getTitle());
holder.total.setText(la.get().getDescription());
holder.setAccount(la.get());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.getAccount() != null) {
callBackFunction.onAccountSelected(holder.getAccount());
} // if (account != null)
} // public void onClick
});
} // if
} // onBindViewHolder
#Override
public int getItemCount() {
return accts.size();
} // getItemCount
RecyclerAdapterAccounts() {
super();
for(int i=0;i<16;i++) {
Account la = new Account();
la.setId((long) i);
la.setTitle("The item number " + i);
la.setDescription("$" + (1000*i));
switch(i%3) {
case 0: la.setIcon("imaged"); break;
case 1: la.setIcon("person_old"); break;
case 2: la.setIcon("pet"); break;
default: la.setIcon("add");
} // switch
accts.add(la);
} // for
} // RecyclerAdapterAccounts
} // class RecyclerAdapterAccounts
At first, In the ExpensesFragment I was getting an Exception that throw the message "Fragment already added". When I changed the ExpensesListFragment to static final, that error was gone.
Again, to recreate the error, you need to run in portrait mode, move through the tabs. Finish on anyone but the first one. Them rotate the device. Tap on the first tab. Then tap on the 3rd one, the one with the recyclerview. Swipe through the list and you will see it is double.
Any help will be appreciated.
Thanks in advance!!!
So I found the answer. ADM (see comment above) sent me to a previous article where part of the solution was to extend ViewPager and override instantiateItem. But I did not want to extend ViewPager.
However, in the same article was another link to this other article where there was the following explanation:
Blockquote By default, [FragmentPagerAdapter] will only preload one Fragment in front and behind the current position (although it does not destroy them unless you are using FragmentStatePagerAdapter).
So, I made TabPagerAdapter extend FragmentStatePagerAdapter instead of FragmentPageAdapter... and that was it!!
Thanks ADM for pointing to the right series of articles.

Android - Recyclerview blank when reopening app after keeping it in background for long

I have the following app structure :
- Activity (ViewPager tabs)
- Fragment A -> Recyclerview with StaggeredGridLayoutManager
- Fragment B -> Recyclerview with GridLayoutManager
The issue : After opening app after keeping it in background for a couple of hours, the recyclerview in Fragment A remains blank but the recyclerview in Fragment B shows data. Both the recyclerviews are using the same instance of arraylist in their adapters.
Issue doesn't occur app is when minimised/resumed in short period of time.
I am able to reproduce this by setting Background process limit to No background processes in developer options. So my guess is this happens each time the process is stopped/killed by the OS.
I am using a class that extends FragmentStatePagerAdapter as adapter for my ViewPager.
Have already tried out the following, but no luck :
https://stackoverflow.com/a/36099641 (can't call getChildFragmentManager from AppCompatActivity)
https://stackoverflow.com/a/25525714
https://stackoverflow.com/a/28262885/6671004
Edit 1: In Fragment A if I replace StaggeredGridLayoutManager by GridLayoutManager, it shows data. So the problem seems to be with the StaggeredGridLayoutManager
Edit 2: Attaching code (Simplified class/variable names for easy understanding)
TabAdapter - adapter for viewpager
public class TabAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public TabAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
Activity - which contains the viewpager
public class MyActivity extends AppCompatActivity implements TabLayout.BaseOnTabSelectedListener {
public static List<MyPojo> mylist = new ArrayList<>();
private TabAdapter adapter;
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentA fragmentA;
private FragmentB fragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
viewPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
adapter = new TabAdapter(getSupportFragmentManager());
mylist.add(...) // arraylist populated
fragmentA = new FragmentA();
fragmentB = new FragmentB();
adapter.addFragment(fragmentA, "A");
adapter.addFragment(fragmentB, "B");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addOnTabSelectedListener(this);
}
... other methods
}
Fragment A - with Staggered Grid Layout
public class FragmentA extends Fragment {
private RecyclerView mRecyclerView;
private FragmentAAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view_a);
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, 1));
adapter = new FragmentAAdapter(getActivity(), MyActivity.myList);
mRecyclerView.setAdapter(adapter);
return view;
}
public void updateRecyclerViewData(){
if (adapter != null)
adapter.notifyDataSetChanged();
}
... other methods
}
Fragment B - with Grid Layout
public class FragmentB extends Fragment {
private RecyclerView mRecyclerView;
private FragmentBAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_b, container, false);
mRecyclerView = view.findViewById(R.id.recycler_view_b);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
adapter = new FragmentBAdapter(getActivity(), MyActivity.myList);
mRecyclerView.setAdapter(adapter);
return view;
}
public void updateRecyclerViewData() {
if (adapter != null)
adapter.notifyDataSetChanged();
}
... other methods
}

Android tabs show wrong fragments

Hello, I'm trying to implement an Activity with tabs. Some tabs contain a fragment that shows simple list, others a tree view like list.
The fragments with simple list work fine, while I'm having troubles with the one which shows tree view like list: the tree are build properly, but I get them in the wrong tabs. In the first tab I always see the content of the second one, and swiping back or expanding/collapsing the tree produces a new unwanted substitution of the whole tree.
I'm struggling to understand what I'm doing wrong. I hope you can suggest me what to do. Thanks in advance!
Here's my code:
Pager Adapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
private final List<ListFragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager)
{
super(manager);
}
#Override
public ListFragment getItem(int index) {
return mFragmentList.get(index);
}
#Override
public int getCount()
{
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(int index, boolean tree) {
Bundle b=new Bundle();
String category= Items.getCategoryByIndex(index);
b.putString(Items.CATEGORY,category);
ListFragment fragment;
if(!tree) {
fragment = new ContentFragment();
} else {
fragment = new TreeFragment();
}
fragment.setArguments(b);
mFragmentList.add(fragment);
mFragmentTitleList.add(Items.getCategoryByIndex(index));
}
}
This is the TreeFragment class:
public class TreeFragment extends TreeViewFragment {
TreeListAdapter mAdapter;
public TreeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle b = getArguments();
String category = (String) b.get(Items.CATEGORY);
GlobalVariables.dataList = Items.getTreeNodeByCategory(category);
GlobalVariables.nodes = TreeViewLists.LoadInitialNodes(GlobalVariables.dataList);
TreeViewLists.LoadDisplayList();
mAdapter = new TreeListAdapter(inflater.getContext());
setListAdapter(mAdapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
and in the activity:
public class MyActivity extends AppCompatActivity {
private ViewPager mViewPager;
private PagerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mAdapter = new PagerAdapter(getSupportFragmentManager());
// (...) Content creation (...)
mAdapter.addFragment(0, true);
mAdapter.addFragment(1, true);
mAdapter.addFragment(2, true);
mAdapter.addFragment(3, true);
mAdapter.addFragment(4, false);
mAdapter.addFragment(5, false);
mViewPager.setAdapter(mAdapter);
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(mViewPager);
}

FragmentStatePagerAdapter items don't load

In my main activity I have multiple Fragments that you can navigate through a bottom navigation (Replace a FrameLayout container in main activity XML)
One of those Fragments contains a ViewPager that should show multiple Fragments (MyFragment) using a FragmentStatePagerAdapter (MyAdapter).
First time I open that Fragment it works just fine but when I navigate to a different one and then come back the first two Fragments in the Pager are grey and unpopulated. Anyone got an idea what the problem might be?
The Adapter is set up like this:
This is called in onFragmentViewCreated
private void setUpHeaderPager() {
featuredAdapter = new MyAdapter(getActivity().getSupportFragmentManager());
myPager.setAdapter(myAdapter);
pageIndicatorView.setViewPager(myPager);
pageIndicatorView.setAnimationType(AnimationType.WORM);
compositeSubscription.add(apiService.getMyPOJOs()
.subscribeOn(networkScheduler)
.observeOn(uiScheduler)
.subscribe(new Action1<List<MyPOJO>>() {
#Override
public void call(List<MyPOJO> myPOJOs) {
myAdapter.setItems(myPOJOs);
pageIndicatorView.setCount(myPOJOs.size());
myPager.setCurrentItem(0);
pageIndicatorView.setSelection(0);
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
}));
}
And this is what the Adapter looks like:
private class MyAdapter extends FragmentStatePagerAdapter {
private List<SomePOJO> items = new ArrayList<>(0);
public void setItems(#Nonnull List<Collection> items) {
this.items = items;
notifyDataSetChanged();
}
FeaturedReleasesAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return MyFragment.newInstance(items.get(position));
}
#Override
public int getCount() {
return items.size();
}
}
Just in case the relevant code of MyFragment:
public class FeaturedReleaseFragment extends BaseFragment {
private MyPOJO someObject = null;
// Bind some views
public static MyFragment newInstance(MyPOJO someObject) {
MyFragment fragment = new MyFragment();
fragment.someObject = someObject;
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_my_fragment, container, false);
ButterKnife.bind(this, rootView);
populate();
return rootView;
}
private void populate() {
if (MyPOJO != null) {
// set some text and load images
}
}
onFragmentViewCreated is called just fine, the adapters getItem is not...
It may be how you're navigating between the bottom navigation fragments and subsequently whats happening with their lifecycle.
If you are using .replace on the FragmentTransaction, try using .show and .hide instead.
Something like the following might do it:
public void navigateToFragment( Fragment frag ) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.hide(currentFragment);
if ( !fragment.isAdded() ) {
transaction.add(R.id.container,fragment)
} else if ( !fragment.isHidden() ) {
transaction.show(fragment);
}
transation.commit();
}

Android ViewPager doesn't show its Fragments correctly

I'm having an issue with the support library ViewPager. That ViewPager lives inside a fragment and it's composed of 3 tabs: one that will show some information, the second and third show a list of elements (so they both are beeing generated from the same fragment). When I scroll from the first to the second one everything works fine but if I try to scroll from the second one to the third something happens to the fragments and they don't show up again even the PagerTabStrip disappears when this happens. Also I tryed using the same type of fragment for the 3 tabs (the one that disappeared with the list)and everything seems to work fine, so I'm quite bugged about this. Also, the only log on the console related to the issue is this one:
W/FragmentManager: moveToState: Fragment state for StoreListFragment{3fb980e7 #2 id=0x7f0d0080 android:switcher:2131558528:2} not updated inline; expected state 3 found 2
This is the code for my parent Fragment:
public class StoreFragment extends Fragment {
#Bind(R.id.pager) ViewPager mPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_store, container, false);
ButterKnife.bind(this, v);
setupViewPager();
return v;
}
private void setupViewPager() {
String[] titles = {getString(R.string.store_information),
getString(R.string.store_offers),
getString(R.string.store_products)
};
mPager.setAdapter(new StoresPagerAdapter(getChildFragmentManager(), titles));
}
}
This is the code for the PagerAdapter:
public class StoresPagerAdapter extends FragmentPagerAdapter {
private String[] mPageTitles;
public StoresPagerAdapter(FragmentManager fm, String[] titles) {
super(fm);
mPageTitles = titles;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return StoreInfoFragment.newInstance();
//return StoreListFragment.newInstance(position);
case 1:
return StoreListFragment.newInstance(position);
case 2:
return StoreListFragment.newInstance(position);
default:
return null;
}
}
#Override
public int getCount() {
return mPageTitles != null ? mPageTitles.length : 0;
}
#Override
public CharSequence getPageTitle(int position) {
return mPageTitles[position];
}
}
And the one for the Fragment:
public class StoreListFragment extends Fragment implements MyListListener {
#Bind(R.id.store_list) RecyclerView mStoreContentView;
private ArrayList<StoreModel> mStoreContents = new ArrayList<>();
public static StoreListFragment newInstance(int page) {
return new StoreListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mStoreContents.add(new Schedule());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_store_list, container, false);
ButterKnife.bind(this, v);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupList();
}
protected void setupList() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
mStoreContentView.setHasFixedSize(true);
mStoreContentView.setLayoutManager(layoutManager);
mStoreContentView.setAdapter(new ArrayAdapter(this, mStoreContents, R.layout.list_elem_locations));
}
#Override
public void onClickElement(int elementId, String elementName) {
Intent i = new Intent(this.getActivity(), DetailActivity.class);
startActivity(i);
}
}
I think your problem is here:
public static StoreListFragment newInstance(int page) {
return new StoreListFragment();
}
You're not using this page anywhere and you're getting two completely same StoreListFragments. You should add:
Bundle args = new Bundle();
args.putInt("key", page);
fragment.setArguments(args);
And then use this differentiation somewhere.

Categories

Resources