ViewPagerFragment选项卡错误

时间:2017-12-01 07:41:53

标签: android android-fragments

我创建了一个viewPager并且正常工作,我的问题是选择一个页面我只能拖动页面,但我想点击选项卡来选择页面。现在我添加一些新代码,但我无法找到此错误

enter image description here

我的代码

public class MainActivity extends FragmentActivity{

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

    final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    Pager adapter = new Pager(getSupportFragmentManager());
    viewPager.setAdapter(adapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
    tabLayout.setupWithViewPager(viewPager);

    viewPager.addOnAdapterChangeListener( new TabLayout.TabLayoutOnPageChangeListener(tabLayout));




    TabLayout.OnTabSelectedListener tabListener = 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) {

        }
    };

1 个答案:

答案 0 :(得分:1)

您不能像viewPager.addOnAdapterChangeListener( new TabLayout.TabLayoutOnPageChangeListener(tabLayout));那样使用,因为addOnAdapterChangeListener()方法期望OnAdapterChangeListener作为参数。您应该在void addOnPageChangeListener (ViewPager.OnPageChangeListener listener)上使用viewPager。它有多个callback method,因此当event的页面发生更改时,您可以检测到viewPager

Reference