3.自定义控件:简易轮播图Demo
2019-05-22 本文已影响18人
BusyBunny
轮播图.gif
轮播图:
- 思路:
- 采用ViewPager加载图片;
- ViewPager的适配器编写;
- 文字跟随图片滑动;
- 小圆点的滑动;
- 向右无限滑动思路;
1. ViewPager适配器编写:
public class MyAdapter extends PagerAdapter {
private static final String TAG = "adapter";
private ObservableArrayList<ImageView> observableImgArrayList;
public MyAdapter(ObservableArrayList<ImageView> observableImgArrayList){
this.observableImgArrayList=observableImgArrayList;
}
@Override
public int getCount() {
return 10000;
}
//复用item
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view==object;
}
//初始化item
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = observableImgArrayList.get(position%5);
container.addView(imageView);
return imageView;
}
//销毁item
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
2.文字跟随banner滑动思路:
添加ViewPager监听:mBinding.viewpager.setOnPageChangeListener
//view:
mBinding.viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//当页面正在滑动的时候
@Override
public void onPageScrolled(int i, float v, int i1) {
}
//当页面被选中停止的时候
@Override
public void onPageSelected(int i) {
viewModel.setDesc(i);
}
//当页面滑动状态被改变的
@Override
public void onPageScrollStateChanged(int i) {
}
});
//ViewModel里面的setDesc方法:
public void setDesc(int position){
desc.set(model.descArray[position]);
}
//Model里面的descArray:
public String[] descArray={"a","b","c","d","e"};
3.小圆点的滑动思路:
依然在ViewPager监听里面实现:
//view:
//记录之前的position
int prevPosition=0;
mBinding.viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//当页面正在滑动的时候
@Override
public void onPageScrolled(int i, float v, int i1) {
}
//当页面被选中停止的时候
@Override
public void onPageSelected(int i) {
//设置圆点滑动:
mBinding.llPoints.getChildAt(i).setEnabled(true);
mBinding.llPoints.getChildAt(prevPosition).setEnabled(false);
//更新:
prevPosition=i;
}
//当页面滑动状态被改变的
@Override
public void onPageScrollStateChanged(int i) {
}
});
4. 无限滑动思路:
假如我们有4张图片,那么我们希望在ViewPagerAdapter中索引为5的时候加载索引为0号的图片,当索引为6的时候加载索引1号图片;
5 ---> 0
6 ---> 1
7 ---> 2
8 ---> 3
依次类推,得到postion%5的关系;
因此改写下ViewPager监听里的onPageSelected方法。
//当页面被选中停止的时候
@Override
public void onPageSelected(int i) {
//设置圆点滑动:
mBinding.llPoints.getChildAt(i%5).setEnabled(true);
mBinding.llPoints.getChildAt(prevPosition%5).setEnabled(false);
//更新:
prevPosition=i%5;
}
//adapter中:
//初始化item
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = observableImgArrayList.get(position%5);
container.addView(imageView);
return imageView;
}