I have a navigation drawer in which there is a ViewPager that extends a Fragment. When i click the item of drawer i open the viewpager in which there are three fragments. It works perfectly. but if i click again the same drawer item to open the viewpager another one time, the viewpager is empty.. I can see the tabs but not the fragments in there. This is the Viewpager:
public class ViewPagerManager extends Fragment {
public static ViewPagerManager instance = null;
Toolbar toolbar;
public static PagerSlidingTabStrip tabs;
public MyPagerAdapter adapter;
public ViewPager pager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tabbed, container, false);
instance = this;
adapter = new MyPagerAdapter(getFragmentManager());
pager = (ViewPager)view.findViewById(R.id.pager);
tabs = (PagerSlidingTabStrip)view.findViewById(R.id.tabs);
pager.setAdapter(adapter);
tabs.setViewPager(pager);
pager.setOffscreenPageLimit(3);
adapter.notifyDataSetChanged();
pager.invalidate();
return view;
}
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "One", "Two", "Three" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Top Rated fragment activity
return new FragmentOne();
case 1:
// Games fragment activity
return new FragmentTwo();
case 2:
// Games fragment activity
return new FragmentThree();
}
return null;
}
}
}
Is it normal? How can i solve? If could help i'm using PagerSlidingTabStrip library.
Use this code
adapter = new MyPagerAdapter(getChildFragmentManager());
instead of
adapter = new MyPagerAdapter(getFragmentManager());
Try to redraw the last selected page when you return to the fragment. I think the viewpager is not cached and you need to reselect the last item. You can override the onresume method.
Related
I have two fragments in my Activity. One contains a viewpager which also has two fragments in it. Everything works fine but the problem is when i re-visit the fragment containing the viewpager from the other fragment, the child fragments in the viewpager are never shown.
This is the fragment containing the viewpager, MainHistoryFragment.java
public class MainHistoryFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.activity_hist, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getActivity(), getActivity().getSupportFragmentManager());
ViewPager viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.getTabAt(0).setIcon(android.R.drawable.ic_dialog_email);
tabs.getTabAt(1).setIcon(android.R.drawable.ic_menu_compass);
}
}
and this is the class subclassing the FragmentPagerAdapter, SectionsPagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2};
private static final int totalTabs = 2;
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
switch (++position){
case 1:
return new HistoryFragment();
case 2:
return new BookmarkFragment();
default:
return null;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
return totalTabs;
}
}
I noticed that the getItem() method of the SectionsPagerAdapter never gets called after a revisit.
Please how do i get my fragments in the viewpager to show after a revisit?
Change this line:
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getActivity(), getActivity().getSupportFragmentManager());
to:
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getActivity(), getActivity().getChildFragmentManager());
You need to use getChildFragmentManager() when u are adding another fragment inside a fragment.
Hope this helps! Happy Coding!
I have a ViewPager.When some data changed,i set the adapter for the ViewPager again by call ViewPager.setAdapter(new Adapter).What i wonder is,the Fragment is re-create (it jump on onDestroyView and then onCreateView) and my Edittext cannot set again the text.And if i remove all Fragment from FragmentTransaction and then setAdapter,the Fragment create a new one -> my Edittext set the text well.So is Fragment recreate itselft NOT from UI thread? ( Because i try the edditext.post and my edditext from first scenario work).Here is the code
Adapter:
public class PagerAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> fmAct;
public PagerAdapter(FragmentManager supportFragmentManager, ArrayList<Fragment> fm) {
super(supportFragmentManager);
fmAct = fm;
}
#Override
public Fragment getItem(int position) {
return fmAct.get(position);
}
#Override
public int getCount() {
return fmAct.size();
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return ((PrFragment) getItem(position)).getFragmentName();
}
what i do when re-set the adapter
fm.clear();
fragmentAttendanceCome = new FragmentAttendanceCome();
fragmentAttendanceCome.setFragmentName(getString(R.string.title_attendance));
fragmentAttendanceCome.setParentActivity(this);
fragmentAssessment = new FragmentAssessment();
fragmentAssessment.setFragmentName(getString(R.string.daily_evaluation));
fragmentAssessment.setParentActivity(this);
fragmentInfo = new FragmentInfo();
fragmentInfo.setParentActivity(this);
fragmentInfo.setFragmentName(getString(R.string.title_infomation));
fm.add(fragmentAttendanceCome);
fm.add(fragmentAssessment);
fm.add(fragmentInfo);
viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), fm));
This is my fragment :
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
textview.setText(data)
// i already Bind it but i lazy to copy it,everything work well
}
I am a newbie with Fragments. I have 5 different Fragmentsin my TabLayout. In each fragment I am loading data from the server.
My problem is as follows:
When the first fragment loads it calls the function and loads data from the server and displays on the RecyclerView.
Then When I swipe to the second tab the server data loads and so on. But when I swipe again to say fragment one the data is loading again from the server and the RecyclerView needs to be set again.
Is there anyway where I can load the server data only once (without saving it to a local database) and set the recyclerview only once so that no matter how many times I swipe the tab the data does not load again? I have referred here but i really didnt understand how to solve my problem.I am posting a snippet of my code.
TabActivity
public class TabActivity extends AppCompatActivity {
ViewPager viewpager;
Toolbar toolbar;
TabLayout tablayout;
ViewPagerAdapter viewPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_activity);
initialize();
}
private void initialize() {
viewpager = (ViewPager) findViewById(R.id.viewpager);
toolbar = (Toolbar) findViewById(R.id.toolbar);
tablayout = (TabLayout) findViewById(R.id.tablayout);
setSupportActionBar(toolbar);
viewPagerAdapter=new ViewPagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(viewPagerAdapter);
tablayout.setTabsFromPagerAdapter(viewPagerAdapter);
tablayout.setupWithViewPager(viewpager);
}
}
class ViewPagerAdapter extends FragmentStatePagerAdapter implements ViewPager.OnPageChangeListener {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:return LocatedEvents.newInstance();
case 1:return QrCodeScanner.newInstance();
case 2:return NewsFeed.newInstance();
case 3:return CreatePoll.newInstance();
case 4:return MyProfile.newInstance();
}
return NewsFeed.newInstance();
}
#Override
public int getCount() {
return 5;
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + (position + 1);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
NewsFeed Fragment
public class NewsFeed extends Fragment {
#Nullable
public static NewsFeed newInstance() {
return new NewsFeed();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsfeed_fragment, container, false);
load_data();
return view;
}
}
Avoid creating new Fragments every time in
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return LocatedEvents.newInstance();
case 1:
return QrCodeScanner.newInstance();
case 2:
return NewsFeed.newInstance();
case 3:
return CreatePoll.newInstance();
case 4:
return MyProfile.newInstance();
}
return NewsFeed.newInstance();
}
Make an array of fragments and pass it to your Adapter.Something like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
initFragments();
}
private void initFragments() {
ArrayList < Fragment > fragmentArrayList = new ArrayList < > ();
fragmentArrayList.add(LocatedEvents.newInstance());
fragmentArrayList.add(QrCodeScanner.newInstance());
fragmentArrayList.add(NewsFeed.newInstance());
fragmentArrayList.add(MyProfile.newInstance();
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), fragmentArrayList); viewpager.setAdapter(viewPagerAdapter); tablayout.setTabsFromPagerAdapter(viewPagerAdapter); tablayout.setupWithViewPager(viewpager);
}
And in your adapter change it to
private ArrayList < Fragment > fragments;
public ViewPagerAdapter(FragmentManager fm, ArrayList < Fragment > fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
here's a portion of my code:
public class MenuExpenses extends Fragment {
private ViewPager viewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.expenses,container, false);
viewPager = (ViewPager) root.findViewById(R.id.pager);
viewPager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) root.findViewById(R.id.tabs);
tabs.setViewPager(viewPager);
return root;
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "Daily", "Recurring" };
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return new MenuExpensesDaily();
case 1: return new IncomeList2();
default: return new MenuExpensesDaily();
}
}
}
}
MenuExpensesDaily & IncomeList2 are both fragments. So how can I set the fragment tag for both of them here?
You can override the instantiateItem method, the save the fragment to a SparseArray/HashMap, then create a method to return the fragment with the position. Now you will be able to access your selected your fragment and set the tag to it.
I have a FragmentList with some items. If I click an item the appropriate Fragment will open which contains a Viewpager. No problem so far but if I go back to the List and click the item again the method getItem(int position) is not called anymore.
Here a link with a similar problem:
Display fragment viewpager within a fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_fragment_runtime, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
indicator = (TitlePageIndicator) view.findViewById(R.id.indicator);
MyFragmentPagerAdapter mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
indicator.setViewPager(mViewPager);
return view;
}
class MyFragmentPagerAdapter extends FragmentStatePagerAdapter implements TitleProvider {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public String getTitle(int position) {
return muxbusTitles[position];
}
#Override
public Fragment getItem(int location) {
return muxbusFragmentList.get(location);
}
#Override
public int getCount() {
return muxbusTitles.length;
}
}
return view;
}
Edit:
If someone is interested,the solution was to extends from PagerAdapter instead of FragmentStatePagerAdpater because the Viewpager is already in a Fragment..
I did have similar problem and after scratching my head for quite some time i made an my own understanding (assumption) that ViewPager is keeping the reference of its child fragments into memory even the hosted Fragment or Activity is destroyed (didn't tested with Activity). So i wrote this method freeFragmentsFromViewPager(). You need to call it from onDestroy() of your Fragment.
/**
* This method free the child fragments from ViewPager as ViewPager keeps the reference
* of child fragments into memory and next time when you again come to visit view pager it won't show the fragment layout
* because it has the reference to the fragment whilst the fragment's view was already destroyed.
*/
private void freeFragmentsFromViewPager()
{
for(int i = 0; i < TabsFragmentPagerAdapter.fragments.length; i++)
{
Fragment fragment = TabsFragmentPagerAdapter.fragments[i];
if(fragment != null)
{
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
TabsFragmentPagerAdapter.fragments[i] = null;
}
}
}
And this is my Adapter code
public class TabsFragmentPagerAdapter extends FragmentPagerAdapter
{
public static final int NUM_TABS = 3;
public static Fragment[] fragments = new Fragment[NUM_TABS];
public TabsFragmentPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
Log.e("TabsFragmentPagerAdapter", "getItem");
Fragment fragment = TabsFragmentFactory.newInstace(position);
fragments[position] = fragment;
return fragment;
}
#Override
public int getCount()
{
return NUM_TABS;
}
#Override
public CharSequence getPageTitle(int position)
{
return TabsFragmentFactory.getName(position);
}