Wai Yan Hein
Wai Yan Hein

Reputation: 14791

Changing tabs of TabLayout programmatically but fragments of ViewPager is not updated

I am developing an Android app. In my app, I am using TabLayout with ViewPager. I need to update the Tabs of TabLayout and its fragments programmatically when an item at the bottom navigation bar is selected. I can update the tabs of TabLayout. But the fragments of pager are not updated.

This is the issue:

enter image description here

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:

 <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.

Upvotes: 2

Views: 2817

Answers (3)

Fly
Fly

Reputation: 1

If your tab is set correctly, under the code where the tab is set, run this again:

mainViewPager.setAdapter(pagerAdapter);

Here is my code:

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

Upvotes: 0

TheHound.developer
TheHound.developer

Reputation: 396

Just Check which layout you are inflating in MatchesFragment class.

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

Upvotes: 0

AssIstne
AssIstne

Reputation: 466

try to add a method to swap the fragment-list and call notifyDataSetChanged() in your adapter like this:

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.

Upvotes: 1

Related Questions