ViewPager
注意事项
- 不知为何将
RecyclerView
和ViewPager
搞混 - 里面有滑动的控件的时候要注意,滑动冲突
- 标签页最好使用
Fragment
,对应的适配器Adapter
也就要继承FragmentPagerAdapter
主要步骤
- 准备几个需要显示的
Fragment
,代码如下:
ManageFragment layManage = new ManageFragment();
SettingFragment laySetting = new SettingFragment();
SurveyFragment laySurvey = new SurveyFragment();
- 讲
Fragment
加添到List<Fragment>
,代码如下:
private List<Fragment> mFragmentList;//Tab页面
mFragmentList = new ArrayList<>();
mFragmentList.add(layManage);
mFragmentList.add(laySetting);
mFragmentList.add(laySurvey);
- 自定义适配器
FragmentPagerAdapter
,代码如下:
public class MainTabAdapter extends FragmentPagerAdapter{
private List<Fragment> mListFragment;
public MainTabAdapter (FragmentManager fragmentManager, List<Fragment> mListFragment){
super(fragmentManager);
this.mListFragment = mListFragment;
}
@Override
public Fragment getItem(int position) {
return mListFragment.get(position);
}
@Override
public int getCount() {
if (mListFragment != null )
return mListFragment.size();
return 0;
}
}//简单框架并没有添加什么操作
- 添加适配器,代码如下:
private ViewPager mViewPager;
mViewPager.setAdapter(new MainTabAdapter(getSupportFragmentManager(),
mFragmentList));
5.配置滑动监听,代码如下:
class TabPagerChangeLister implements ViewPager.OnPageChangeListener{
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onPageSelected(int position) {
Animation animation= null;
switch (position){
case PAGE_MANAGE:
if (currentIndex == PAGE_SETTING){
}else if(currentIndex == PAGE_SURVEY ){
}
break;
case PAGE_SETTING:
if (currentIndex == PAGE_MANAGE){
}else if (currentIndex == PAGE_SURVEY){
}
break;
case PAGE_SURVEY:
if (currentIndex == PAGE_MANAGE){
}else if (currentIndex == PAGE_SETTING){
}
break;
default:
break;
}
}
}
6.(可选)需要标签切换的时候可以添加几个TextView
,代码如下:
private TextView manage;
private TextView setting;
private TextView survey;
manage = (TextView)findViewById(R.id.tv_tab_manage);
setting = (TextView)findViewById(R.id.tv_tab_setting);
survey = (TextView)findViewById(R.id.tv_tab_survey);
manage.setOnClickListener(this);
setting.setOnClickListener(this);
survey.setOnClickListener(this);
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.tv_tab_manage:
mViewPager.setCurrentItem(PAGE_MANAGE);
break;
case R.id.tv_tab_setting:
mViewPager.setCurrentItem(PAGE_SETTING);
break;
case R.id.tv_tab_survey:
mViewPager.setCurrentItem(PAGE_SURVEY);
break;
default:
break;
}
}
问题
因为没有深入体验,相信在滑动监听,适配器中可以做很多事,慢慢发掘
特别鸣谢
灵魂导师- KingJA
网友评论