简体   繁体   English

以编程方式更改TabLayout的选项卡,但未更新ViewPager的片段

[英]Changing tabs of TabLayout programmatically but fragments of ViewPager is not updated

I am developing an Android app. 我正在开发一个Android应用程序。 In my app, I am using TabLayout with ViewPager. 在我的应用程序中,我将TabLayout与ViewPager一起使用。 I need to update the Tabs of TabLayout and its fragments programmatically when an item at the bottom navigation bar is selected. 当选择底部导航栏中的一个项目时,我需要以编程方式更新TabLayout的选项卡及其片段。 I can update the tabs of TabLayout. 我可以更新TabLayout的标签。 But the fragments of pager are not updated. 但是寻呼机的片段不会更新。

This is the issue: 这是问题:

在此处输入图片说明

As you can see in the above, tabs are changed but its fragments are not changed. 如上所示,选项卡已更改,但其片段未更改。 List Fragment is always displayed. 列表片段始终显示。 All the fragments are just the same with the first tab selected. 所有片段都与选择的第一个选项卡相同。 I mean fragments are not changing at all. 我的意思是片段根本没有改变。

This is my XML file for the tabs and view pager: 这是我用于标签和视图分页器的XML文件:

 <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">


        <android.support.design.widget.TabLayout
            android:id="@+id/ma_tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/ma_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

This is my whole activity: 这是我的整个活动:

public class MainActivity extends AppCompatActivity {

    private BottomBar bottomBar;
    private TabLayout topTabLayout;
    private ViewPager mainViewPager;
    private MainPagerAdapter pagerAdapter;
    private ArrayList<Fragment> pagerFragments;
    private ArrayList<String> pagerTitleList;
    protected TfrApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        app = (TfrApplication)getApplication();
        setContentView(R.layout.activity_main);
        initialize();
        initViews();
        setUpViews();
    }

    private void initialize()
    {
        pagerFragments = new ArrayList<Fragment>();
        pagerTitleList = new ArrayList<String>();
    }

    private void initViews()
    {
        bottomBar = (BottomBar)findViewById(R.id.ma_bottom_action_bar);
        mainViewPager = (ViewPager)findViewById(R.id.ma_viewpager);
        topTabLayout = (TabLayout)findViewById(R.id.ma_tab_layout);
    }

    private void setUpViews()
    {
        pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(),pagerFragments,pagerTitleList);
        mainViewPager.setAdapter(pagerAdapter);
        topTabLayout.setupWithViewPager(mainViewPager);
        setUpBottomBar();
    }

    private void clearPagerFragments()
    {
        if(pagerAdapter!=null && pagerFragments!=null && pagerFragments.size()>0)
        {
            pagerFragments.removeAll(pagerFragments);
            pagerTitleList.removeAll(pagerTitleList);
            pagerAdapter.notifyDataSetChanged();
        }
    }

    private void setUpNewsPagerFragments()
    {
        NewsFragment latestNewsFragment = new NewsFragment();
        Bundle latestNewsBundle = new Bundle();
        latestNewsBundle.putInt(NewsFragment.FIELD_CATEGORY_ID,0);
        latestNewsBundle.putInt(NewsFragment.FIELD_LEAGUE_ID,0);
        latestNewsBundle.putInt(NewsFragment.FIELD_COUNTRY_ID,0);
        latestNewsBundle.putInt(NewsFragment.FIELD_TEAM_ID,0);
        latestNewsFragment.setArguments(latestNewsBundle);
        pagerTitleList.add("LATEST");
        pagerFragments.add(latestNewsFragment);

        PrioritizedTeamsFragment teamsFragment = new PrioritizedTeamsFragment();
        pagerTitleList.add("TEAMS");
        pagerFragments.add(teamsFragment);

        NewsFragment articlesFragment = new NewsFragment();
        Bundle articlesBundle = new Bundle();
        articlesBundle.putInt(NewsFragment.FIELD_CATEGORY_ID, 0);
        articlesBundle.putInt(NewsFragment.FIELD_LEAGUE_ID, 0);
        articlesBundle.putInt(NewsFragment.FIELD_COUNTRY_ID, 0);
        articlesBundle.putInt(NewsFragment.FIELD_TEAM_ID, 0);
        articlesFragment.setArguments(articlesBundle);
        pagerTitleList.add("ARTICLES");
        pagerFragments.add(articlesFragment);

        TopFragment topFragment = new TopFragment();
        pagerTitleList.add("TOP 10");
        pagerFragments.add(topFragment);
    }

    private void setUpMatchesPagerFragments()
    {
        MatchesFragment matchesFragment = new MatchesFragment();
        pagerTitleList.add("MATCHES");
        pagerFragments.add(matchesFragment);

        StatisticsFragment statisticsFragment = new StatisticsFragment();
        pagerTitleList.add("STATISTICS");
        pagerFragments.add(statisticsFragment);
    }

    private void setUpBottomBar()
    {
        bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelected(int tabId) {
                switch (tabId){
                    case R.id.bottom_tab_news:
                        clearPagerFragments();
                        setUpNewsPagerFragments();
                        pagerAdapter.notifyDataSetChanged();
                        break;
                    case R.id.bottom_tab_matches:
                        clearPagerFragments();
                        setUpMatchesPagerFragments();
                        pagerAdapter.notifyDataSetChanged();
                        topTabLayout.getTabAt(0).select();
                        break;

                    case R.id.bottom_tab_meme:
                        Toast.makeText(getBaseContext(),"MEME",Toast.LENGTH_SHORT).show();
                        break;

                    case R.id.bottom_tab_settings:
                        Toast.makeText(getBaseContext(),"Settings",Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }
}

I showed the whole activity because code the whole activity dealing with that problem. 我展示了整个活动,因为对解决该问题的整个活动进行了编码。 Besides, the whole activity only contains code for creating tabs, view pager and bottom bar. 此外,整个活动仅包含用于创建选项卡,查看寻呼机和底部栏的代码。 All are connected. 全部连接。

This is my view pager adapter: 这是我的视图寻呼机适配器:

public class MainPagerAdapter extends FragmentPagerAdapter {
    private ArrayList<Fragment> fragmentList;
    private ArrayList<String> titleList;

    public MainPagerAdapter(FragmentManager fragmentManager,ArrayList<Fragment> fragmentsParam,ArrayList<String> titlesParam)
    {
        super(fragmentManager);
        this.fragmentList = fragmentsParam;
        this.titleList = titlesParam;
    }

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

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titleList.get(position);
    }
}

Why is the content or fragments of view pager are not changed when tabs are changed? 更改选项卡时,为什么视图分页器的内容或片段没有更改? What is wrong with my code? 我的代码有什么问题?

As you can see on bottom item selected listener I tried to set the selected fragment like this: 正如您在选择的侦听器的底部项上看到的那样,我试图像这样设置选择的片段:

topTabLayout.getTabAt(0).select();

I tried this as well: 我也尝试过这个:

mainViewPager.setCurrentItem(0);

Both are not working. 两者都不起作用。

try to add a method to swap the fragment-list and call notifyDataSetChanged() in your adapter like this: 尝试添加一种方法来交换片段列表并在适配器中调用notifyDataSetChanged()

public void notifyDataSetChanged(List<Fragment> list) {
    fragmentList.removeAll();
    fragmentList.addAll(list);
    notifyDataSetChanged();
}

changing data in activity and call adapter.notifyDataSetChanged() may fail to update your view.You can log in getItem() to check if the adapter knows the data set has changed. 在活动中更改数据并调用adapter.notifyDataSetChanged()可能无法更新您的视图。您可以登录getItem()来检查适配器是否知道数据集已更改。

Just Check which layout you are inflating in MatchesFragment class. 只需检查MatchesFragment类中要放大的布局即可。

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.matches_fragment, container, false);
}

If your tab is set correctly, under the code where the tab is set, run this again: 如果选项卡设置正确,请在设置选项卡的代码下再次运行此命令:

mainViewPager.setAdapter(pagerAdapter); mainViewPager.setAdapter(pagerAdapter);

Here is my code: 这是我的代码:

selectedTab = 0; tabLayout.getTabAt(selectedTab).select(); viewPager.setAdapter(tabsAdapter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM