我创建了一个viewPager并且正常工作,我的问题是选择一个页面我只能拖动页面,但我想点击选项卡来选择页面。
我也添加(编译'com.android.support:design:26.0.0-alpha1')
我的FragmentPagerAdapter代码
public class Pager extends FragmentPagerAdapter {
public Pager(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return First_Activity.newInstance();
case 1:
return Second_Activity.newInstance();
case 2:
return Third_Activity.newInstance();
default:
return First_Activity.newInstance();
}
}
@Override
public int getCount() {
return 3;
}
// --->>>Title Pages<<<---
@Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0:
return " page 1 ";
case 1:
return " page 2 ";
case 2:
return " page 3 ";
default:
return "";
}
}
}
我的MainActivity代码
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);
}
}
答案 0 :(得分:1)
首先在onCreate()中声明此行:
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
Here , tabLayout is layout of your tabs you created in layout.
现在添加此功能:
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)
{ }
};
此代码肯定会对你有用。