简体   繁体   English

Android:更新标签内容

[英]Android: Updating tab content

I am new to Android development. 我是Android开发的新手。 I have a ViewPager which holds TabLayout (that has fixed number of tabs). 我有一个ViewPager ,其中包含TabLayout (具有固定数量的标签)。 The ViewPager has SectionPagerAdapter (that has a fragment corresponding to tabs). ViewPager具有SectionPagerAdapter (具有与选项卡相对应的片段)。

Now, I want to update tab content when user selects the tab and as it becomes visible (or when user wants to refresh the content). 现在,我想在用户选择选项卡并使其可见时(或当用户想要刷新内容时)更新选项卡内容。

But I am not sure which is correct way I can do this. 但是我不确定哪种方法正确。

So far till now I found two solutions: 到目前为止,我发现了两种解决方案:

1) Add listener to TabLayout : 1)将侦听器添加到TabLayout

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() 
{
    @Override
    public void onTabSelected(TabLayout.Tab tab) 
    {
        mViewPager.setCurrentItem(tab.getPosition());
        // Update tab containts here
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) 
    {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) 
    {

    }
});

2) Use ViewPager.OnPageChangeListener to get callbacks for when a page fragment (inside Tab) becomes visible: 2)使用ViewPager.OnPageChangeListener来获取页面片段(在Tab内)可见时的回调:

viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() 
{
    @Override
    public void onPageSelected(int position) 
    {
        // Update tab containts here
    } 
});

Can someone expert in this please advice me? 有人可以请教我吗?

The way a viewpager adapter works (with tabs) is that once you add your fragments to the viewpager, then you basically need to add content to your fragments and let the adapter manage which fragment is visible when a given tab is selected. viewpager适配器(带有选项卡)的工作方式是,一旦将片段添加到viewpager,则基本上需要向片段中添加内容,并让适配器管理选择给定选项卡时可见的片段。

So, by simply using : OnTabSelectedListener interface on your tabLayout, all you need to do is `setCurrentItem(tab.getPosition()); 因此,只需在OnTabSelectedListener上使用OnTabSelectedListener接口,只需要做setCurrentItem(tab.getPosition()); on your viewPager reference (from your layout). 在您的viewPager参考上(来自您的布局)。

You can have a method like this to add fragments to your viewPagerAdapter: 您可以使用如下方法将片段添加到viewPagerAdapter中:

private void setupViewPager(ViewPager viewPager){
    //then create an instance of your ViewPagerAdapter class here
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

    //then add fragments for each TAB here
    //by calling a method inside your Adapter like this
    adapter.addFrag(new FragmentOne(), "TITLE HERE");
    adapter.addFrag(new FragmentTwo(), "TITLE TWO");

    //Now set your adapter here
    viewPager.setAdapter(adapter);
}

Now in your fragments, you can show different content accordingly. 现在,在片段中,您可以相应地显示不同的内容。

I hope this helps! 我希望这有帮助!

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

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