How to update fragment content from activity (viewpager)?

前端 未结 3 630
庸人自扰
庸人自扰 2020-12-08 21:48

I have a simple viewPager with two fragments. Each fragment contains a TextView. I would like to be able to update the text of the current textView displayed from the activi

相关标签:
3条回答
  • 2020-12-08 22:21

    In your MyPagerAdapter class, Android calls getItem(...) only if it wants to create new Fragments. So it's problematic to use references there instead you should instatiate the fragments.

    Check this Answer support-fragmentpageradapter-holds-reference-to-old-fragments

    0 讨论(0)
  • 2020-12-08 22:26

    I solved this issue like this, create the adapter like this

    package com.yubraj.sample.adapter;
    
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentStatePagerAdapter;
    
    import com.yubaraj.sample.activities.RashiFragment;
    import java.util.List;
    
    
    public class PageSliderAdapter extends FragmentStatePagerAdapter {
        static String[] titleList = new String[] { "today",
                "this month", "this year" };
        List<String> rashi;
        // private static String TAG = "pagerscreenslider";
    
        public PageSliderAdapter(FragmentManager fm, List<String> rashiList) {
            super(fm);
            this.rashi = rashiList;
        }
        public void updateData(List<String> rashisList){
            rashi.clear();
            this.rashi = rashisList;
            notifyDataSetChanged();
        }
        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return POSITION_NONE;
        }
    
        @Override
        public Fragment getItem(int position) {
            Fragment fragment = new RashiFragment();
            Bundle bundle = new Bundle();
            bundle.putString("RASHI", rashi.get(position));
            bundle.putInt("RASHI_TYPE", position);
            fragment.setArguments(bundle);
            return fragment;
        }
    
        @Override
        public int getCount() {
            return titleList.length;
        }
    
        @Override
        public String getPageTitle(int position) {
            return titleList[position];
        }
    
    
    }
    

    Then from Your activity

    List<String> rashiCollection = getJSONFromDb(Dates);
    adapter.updateData(rashiCollection);
    
    0 讨论(0)
  • 2020-12-08 22:27
    @Override
        public int getItemPosition(Object object) {
        XXXFragment fragment = (XXXFragment) object;
            if(…condition){
        fragment.refresh(…);
        }
            return super.getItemPosition(object);
        }
    

    override the above. when you call notifyDataSetChanged(), the above method's triggered. do your refresh as you can.

    0 讨论(0)
提交回复
热议问题