xml的布局文件弄好了,我们就要给几个button设置点击事件。
1.点击跳转,那我们需要给他设置跳转页
2.如何把几个子类添加到ViewPager
2.绑定Click事件
建一个基类BasePager,让五个类去继承它。
</pre><pre name="code" class="java">public class BasePager {
public Activity mActivity;
public View mRootView;//当前页面的布局对象
public BasePager(Activity activity)
{
mActivity = activity;
mRootView = initView();
}
public View initView() {
View view = View.inflate(mActivity, R.layout.base_pager, null);
return view;
}
其中一个子类
public class HomePager extends BasePager {
public HomePager(Activity activity) {
super(activity);
// TODO Auto-generated constructor stub
}
public void initData(){
}
}
viewpager,绑定RadioGroup click监听事件
public class ContentFragment extends BaseFragment {
private NoScrollViewPager mViewPager;
private RadioGroup rgGroup;
private ArrayList<BasePager> mPagers;
//初始化数据
public View initView() {
View view = View.inflate(mactivity, R.layout.fragment_content, null);
mViewPager = (NoScrollViewPager) view.findViewById(R.id.vp_content);
rgGroup = (RadioGroup) view.findViewById(R.id.rg_group);
return view;
}
//将五个子类添加到Viewpager
public void initData() {
mPagers = new ArrayList<BasePager>();
mPagers.add(new HomePager(mactivity));
mPagers.add(new NewCenterPager(mactivity));
mPagers.add(new GovAffairsPager(mactivity));
mPagers.add(new SmartServicePager(mactivity));
mPagers.add(new SettingPager(mactivity));
mViewPager.setAdapter(new ContentAdapter());
// RadioGroup监听事件
rgGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_home:
mViewPager.setCurrentItem(0, false);
break;
case R.id.rb_news:
mViewPager.setCurrentItem(1, false);
break;
case R.id.rb_smart:
mViewPager.setCurrentItem(2, false);
break;
case R.id.rb_gov:
mViewPager.setCurrentItem(3, false);
break;
case R.id.rb_setting:
mViewPager.setCurrentItem(4, false);
break;
default:
break;
}
}
});
class ContentAdapter extends PagerAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
return mPagers.size();
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == arg1;
}
// 初始化item布局
public Object instantiateItem(ViewGroup container, int position) {
BasePager pager = mPagers.get(position);
View view = pager.mRootView;
//pager.initData(); , 初始化item,默认会加载下一个页面,为了节省流量和性能,对其优化
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}