提问者:小点点

viewPager2的实现


我实现了viewPager,它工作得很好,但现在我想移动到viewPager2,但我不知道该写什么而不是addOnPageChangeListener,因为我有一个错误,在viewPager2中没有这样的函数。这是我的主要活动代码:

package com.example.viewpager;

import androidx.appcompat.app.AppCompatActivity;

import android.net.Uri;
import android.os.Bundle;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity implements 
Tab1.OnFragmentInteractionListener, Tab2.OnFragmentInteractionListener, 
Tab3.OnFragmentInteractionListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
    tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager2 viewPager = (ViewPager2) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), getLifecycle());
    viewPager.setAdapter(adapter);
//        viewPager.setOffscreenPageLimit(2);
   // new ViewPager2.OnPageChangeCallback(new 
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

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

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

        }
    });
}

@Override
public void onFragmentInteraction(Uri uri){

}

}


共1个答案

匿名用户

是的,那个链接有帮助。我更改了这些代码行:

 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

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

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

        }
    });

    viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            tabLayout.selectTab(tabLayout.getTabAt(position));
        }
    });