We use viewpager to implement the carousel, so the first step is naturally to mark the viewpager in the xml file
Then implement the relevant logic in the java main file
1. Let's first come to a data source, statically added data
2. Viewpager needs an adapter, we come to a custom adapter inherited from pageradapter, to achieve the basic four methods
3. Instantiate the adapter in the main java file and pass the data we prepared.
Fourth, set the content of the adapter The content
required by the four methods has been annotated
public class MyDemoPagerAdapter extends PagerAdapter {
private List<Integer> list = new ArrayList<>();
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
// 因为我们返回的长度是最大长度,所以这边不能直接按照position获取,所以在这余一下
int i = position % list.size();
// 轮播图中是图片,所以来一个图片
ImageView imageView = new ImageView(container.getContext());
// 按照position,也就是我们余后的索引,得到每个图片资源
Integer integer = list.get(i);
// 给图片设置内容
imageView.setImageResource(integer);
// 设置好资源后需要将imageview这个东西添加到container中
container.addView(imageView);
// 最后返回我们的imageview
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
// 切换视图的时候删除object对象
container.removeView((View) object);
}
@Override
public int getCount() {
// 因为轮播图要一直向下滑动,所以只返回数据长度的话就会滑到头,我们就给他最长的长度
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
// 官方推荐 view==object
return view==object;
}
public void setData(List<Integer> list) {
this.list = list;
}
}
5. Check the effect of the semi-finished product
(you can go down now, but you can't slide left)
Six, to achieve the effect of sliding left
// 设置viewpager所在的条目位置,我们给他折中
mydemo_viewpager.setCurrentItem(Integer.MAX_VALUE/2);
Effect picture:
Although it can slide left and right, it can slide infinitely, but it can’t rotate automatically.
Seven, realize automatic carousel
In the java main code, a handler is used to realize the relevant logic, and the comments are clearly written
Handler handler = new Handler();
// 来一个定时的
handler.postDelayed(new Runnable() {
@Override
public void run() {
// 得到viewpager的当前条目
int currentItem = mydemo_viewpager.getCurrentItem();
// 让当前条目自增1
currentItem++;
// 设置新的条目
mydemo_viewpager.setCurrentItem(currentItem);
// 让他循环一次后,停歇一秒继续执行此(当前)过程
handler.postDelayed(this,1000);
}
}, 3000);
To sum up, a simple semi-finished carousel is just fine. There are also click events and indicators. I have a chance (learned) to make up