How to refresh a Fragment of a FragmentPagerAdapte

2019-02-06 06:39发布

问题:

I have got 2 tabs called tab1 (home) and tab2 (profile) using TabPageIndicator and FragmentPagerAdapter libraries.

In tab2, I have a button named "Log in" (tab2 inflates abc.xml).

When users click "log in" button, the app will show a login form in a new activity. After logging in, the activity finishes and the content view of tab2 will change ( it shows user's profile because it will inflate xyz.xml). How can I do that?

public class MainActivity extends SherlockFragmentActivity {
    private static String[] TAB_NAMES = null;
    private Context context = this;
    private static FragmentPagerAdapter adapter ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (TAB_NAMES == null) {
            TAB_NAMES = new String[] {
                    getResources().getString(R.string.tab_home),
                    getResources().getString(R.string.tab_profile) };
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        adapter = new TabsAdapter(
                getSupportFragmentManager());

        ViewPager pager = (ViewPager) findViewById(R.id.pager);

        pager.setAdapter(adapter);


        TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
        indicator.setViewPager(pager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater infalter = getSupportMenuInflater();
        infalter.inflate(R.menu.main_menu, menu);
        return true;
    }

    class TabsAdapter extends FragmentPagerAdapter {
        public TabsAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0:
                return HomeFragment.getInstance();
            case 1:
                return new ProfileFragment();

            default:
                return HomeFragment.getInstance();
            }
        }
        }

回答1:

You can use FragmentStatePagerAdapter instead of FragmentPagerAdapter

You can try like this:

private static FragmentStatePagerAdapter adapter ;
private static String[] TAB_NAMES = null;

@Override
protected void onCreate(Bundle savedInstanceState) {

    if (TAB_NAMES == null) {
        TAB_NAMES = new String[] {
                getResources().getString(R.string.tab_home),
                getResources().getString(R.string.tab_profile) };
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return HomeFragment.getInstance();
                case 1:
                    return new ProfileFragment();

                default:
                    return HomeFragment.getInstance();
            }
        }

        @Override
        public int getCount() {
            return TAB_NAMES.length;
        }

        @Override
        public int getItemPosition(Object fragItem) {
            int position = 0;
            if (fragItem instanceof HomeFragment) {
                position = 0;
            } else if (fragItem instanceof  ProfileFragment) {
                position = 1;
            }
            return (position >= 0) ? position : POSITION_NONE;
        }
    }

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(adapter);


    TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
    indicator.setViewPager(pager);

}

Reference

You can check this solution.



回答2:

You can use startActivityForResult(or broadcast/receiver) to get the result from the activity. Then use adapter.notifyDataSetChanged to refresh the fragment.

About refreshing the ViewPager, more detail:

ViewPager PagerAdapter not updating the View



回答3:

I've tried a lot of solutions i found in google and stackoverflow about this problem. All of them did not work correctly. Also tutorials in official google android developer pages didn't work.

I implemented ViewPageIndicator to my application and tried to create an imageslider. I have dynamic urls for images comes from on service callback success. So i have to set my viewpager adapter and indicator in OnResume. When i set everything was ok i load fragments in onResume and after OnStop i reload them. But when i send app to background and open some other apps i realized after onResume my slider cant reload images.

After wasting my time, i tried to understand lifecyle of fragments which i created in fragmentpageradapter getItem clearly with logging and debugging onCreateView and onResume events.

If you create your fragments like

Fragment myFragment = new Fragment(url,position);

After you stop your activity and open some other applications, you loose your vars which you set on constructor of your custom fragment. When i realized this situation i tried bundle approach.

Here is my custom FragmentPagerAdapter (I used google's sample)

public class ScreenSlidePageAdapter extends FragmentPagerAdapter implements IconPagerAdapter {

        ArrayList<String> urls;

        public ScreenSlidePageAdapter(ArrayList<String>urls,FragmentManager fm) {
            super(fm);
            this.urls = urls;
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }

        @Override
        public Fragment getItem(int position) {
            SliderFragment sliderFragment = new SliderFragment();
            Bundle bundle = new Bundle();
            bundle.putString("url",urls.get(position));
            sliderFragment.setArguments(bundle);
            return sliderFragment;
        }

    @Override
    public int getIconResId(int index) {
        return R.drawable.notification_circle;
    }

    @Override
    public int getCount() {
        return this.urls.size();
    }

} 

My custom FragmentPagerAdapter implements IconPagerAdapter. Be careful about that.

And my custom SliderFragment:

public class SliderFragment extends Fragment {

    private String url;
    private int position;
    private boolean clickable;

    public SliderFragment() {
    }

    public SliderFragment(String url, int position, boolean clickable) {

        this.url = url;
        //this.position = position;
        //this.clickable = clickable;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.layout_fragment_slider, container, false);


            this.url = getArguments().getString("url");

            ImageView imageView = (ImageView) rootView.findViewById(R.id.iv_image);
            com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(Constants.URL_PREFIX + url, imageView);


                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(),SliderActivity.class);
                        intent.putExtra("url",url);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.anim_slide_in_left,
                                R.anim.anim_slide_out_left);
                    }
                });


        return rootView;
    }

And finally my loadSlider method which loads slider items

private void loadSlider() {

        pager = (ViewPager) findViewById(R.id.dealdetailpager);

        ScreenSlidePageAdapter screenSlidePageAdapter = new ScreenSlidePageAdapter(dealDetail.getImages(),getSupportFragmentManager());
        pager.setAdapter(screenSlidePageAdapter);

        circlePageIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
        circlePageIndicator.setViewPager(pager);

        sliderThread = new SliderThread(true, 0);
        sliderThread.start();
    }

I could not have chance to check if my slider fragments are being updated but at least fragments live after OnStop and thats what i needed most.



回答4:

I was also facing the same issue, So i resolved it on my way:

Just refresh your HomeFragment or ProfileFragment by overriding onResume method.

In onResume Method you can refresh your ListFragment or Fragment easily.