一.主方法
注意:继承的是 FragmentActivity
private ViewPager pager;
private RadioGroup group;
int[] ids = { R.id.temai, R.id.gouwuche, R.id.shouye };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.viewpager);
group = (RadioGroup) findViewById(R.id.radiogroup);
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
//点击的id checkedId
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for(int i=0;i<ids.length;i++){
RadioButton rb= (RadioButton) findViewById(ids[i]);
if(checkedId==ids[i]){ //依次判断当前位置的值 是否和 checkedIdid
pager.setCurrentItem(i); //把vp中相应的位置进行显示
rb.setTextColor(Color.RED);
}else{
rb.setTextColor(Color.BLACK);
}
}
}
});
// 进行添加
List.add(new Frag_one());
List.add(new Frag_two());
List.add(new Frag_three());
// new 一个适配器
MyFragment adapter = new MyFragment(getSupportFragmentManager(), List);
//将适配器放入
pager.setAdapter(adapter);
}
二. 适配器
注意:继承的是FragmentPagerAdapter
public class MyFragment extends FragmentPagerAdapter {
List<Fragment> list;
public MyFragment(FragmentManager fm, List<Fragment> list) {
super(fm);
this.list = list;
}
@Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
}