Search code examples
androidandroid-studiotabsandroid-viewpager

How to change PageView after change tabs?


I apologize immediately for my English). I found a code from a google, I installed it on an android studio, but the result of the code is not the one I want. When I click on the tab the control comes to another (for example, item1, item2, item3, item4) from item1 to item2 come in but the ListViev elements remain the same. How to make PageViev elements change after clicking tab control?

  final TabLayout tab=findViewById(R.id.tabs);
    final ViewPager viewPager=findViewById(R.id.view_pager);
    tab.removeAllTabs();
    for (int k = 0; k <GoodsGroupList.size(); k++) {
       tab.addTab(tab.newTab().setText("" + GoodsGroupList.get(k)));
    }

    tab.setTabMode(TabLayout.MODE_SCROLLABLE);  
    PlansPagerAdapter adapter = new PlansPagerAdapter(getSupportFragmentManager(), tab.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));

Fragment_home.xml

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#000000"
    tools:ignore="MissingConstraints" />

<androidx.viewpager.widget.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="48dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_below="@+id/tabs"/>

Fragment_menu.xml

<ListView
    android:id="@+id/ListViewer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@drawable/list_divider"
    tools:ignore="MissingConstraints" />

Solution

  • Tabview does not change tab on touch

    I found a similar problem and added part of the code and in May the problem was resolved.

    tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    viewPager.setCurrentItem(tab.getPosition());
                    Log.d("Tab", String.valueOf(tab.getPosition()));
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
    
                }
    
                @Override
                public void onTabReselected(TabLayout.Tab tab) {
    
                }
            });