选项卡布局中的数据不会刷新

时间:2016-09-14 12:38:20

标签: android android-viewpager android-tablayout

在我的应用程序中,我使用了带有viewpager的tab-layout,最初所有选项卡都正常工作,但是当从服务器更新数据时,它不会在选项卡中更新。它仅显示旧值。如果我终止该应用并再次打开,则会反映新值。如何立即更新数据。

提前致谢

1 个答案:

答案 0 :(得分:0)

对于任何具有相同大小写的正文,您都可以从here实现Viewpager2 然后添加adapter.notifyItemChanged(position);,如下所示:

viewPager = (ViewPager2) android.findViewById(R.id.view_pager);
    tabLayout = (TabLayout) android.findViewById(R.id.tab_layout);


    ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager(),getLifecycle());
    viewPager.setAdapter(adapter);

    viewPager.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);
            adapter.notifyItemChanged(position);
        }
    });
        new TabLayoutMediator(tabLayout, viewPager, true,
            (tab, position) -> {



                switch (position) {
                    case 0:
                        tab.setText(getString(R.string.tab1));
                        break;
                    case 1:
                        tab.setText(getString(R.string.tab2));
                        break;
                    case 2:
                        tab.setText(getString(R.string.tab3));
                        break;
                    case 3:
                        tab.setText(getString(R.string.tab4));
                        break;
                    default:
                        tab.setText(getString(R.string.tab1));
                        break;
                }

            }).attach();

每次单击选项卡时,以上代码都会刷新代码。但滑动Viewpager时不会。

适配器的代码是:

public class ViewPagerAdapter extends FragmentStateAdapter {

    private static final int CARD_ITEM_SIZE = 4;

    public ViewPagerAdapter(@NonNull FragmentManager fragmentActivity, @NonNull Lifecycle life) {
        super(fragmentActivity,life);
    }


    @NonNull
    @Override
    public Fragment createFragment(int position) {
        //return CardFragment.newInstance(position);
        switch (position) {
            case 0:
                return FragmentTab1.newInstance();
            case 1:
                return FragmentTab2.newInstance();
            case 2:
                return FragmentTab3.newInstance();
            case 3:
                return FragmentTab4.newInstance();
            default:
                return FragmentTab1.newInstance();
        }

    }

    @Override
    public int getItemCount() {
        return CARD_ITEM_SIZE;
    }


}