public class Frag_01 extends Fragment{
int arr[]={R.drawable.banner01,R.drawable.banner02,R.drawable.banner03};
private ViewPager pager;
private RadioGroup radioGroup;
private ArrayList<ImageView> list;
//无限轮播
private Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
int item = pager.getCurrentItem()+1;
pager.setCurrentItem(item);
handler.sendEmptyMessageDelayed(0, 1000);
};
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_01, null, false);
//找控件
pager = (ViewPager) view.findViewById(R.id.pager2);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup2);
list = new ArrayList<ImageView>();
RadioGroup.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.leftMargin = 8;//设置小圆点距离
for (int i = 0; i < arr.length; i++) {
ImageView imageView = new ImageView(getActivity());
imageView.setImageResource(arr[i]);
list.add(imageView);
//创建小圆点
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setButtonDrawable(R.drawable.sel_button);
//把小圆点添加radioGroup
radioGroup.addView(radioButton, params);
}
//第一个默认选中
radioGroup.check(radioGroup.getChildAt(0).getId());
handler.sendEmptyMessageDelayed(0, 2000);
//适配器
pager.setAdapter(new PagerAdapter() {
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 ==arg1;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Integer.MAX_VALUE;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
int a = position%list.size();
ImageView imageView = list.get(a);
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position,
Object object) {
container.removeView((View) object);
}
});
//小圆点跟着动
pager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
int arg = arg0%list.size();
radioGroup.check(radioGroup.getChildAt(arg).getId());
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
return view;
}
}