本文实例为大家分享了使用ViewPager2实现轮播图效果的具体代码,供大家参考,具体内容如下
0.实现效果

1.添加依赖
dependencies {
...
implementation 'androidx.viewpager2:viewpager2:1.0.0'
}
2.设计布局
使用CardView实现圆角的效果,并在父布局的右下角放一个线性布局,用来动态添加指示点。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:padding="10dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="200dp"> <androidx.cardview.widget.CardView android:layout_width="match_parent" android:layout_height="match_parent" app:cardCornerRadius="10dp" app:cardElevation="0dp"> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/viewpager2" android:layout_width="match_parent" android:layout_height="match_parent" /> </androidx.cardview.widget.CardView> <LinearLayout android:id="@+id/container_indicator" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_alignParentEnd="true" android:layout_alignParentBottom="true" android:layout_marginEnd="5dp" android:layout_marginBottom="5dp"/> </RelativeLayout> </RelativeLayout>
3.实现Adapter
ViewPager2是使用RecyclerView实现的,适配器的写法与使用RecyclerView类似。
要实现"无限"轮播,需要在getItemCount()方法中返回一个较大的值,这里返回的是Integer.MAX_VALUE.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/container" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textSize="20sp"/> </RelativeLayout>
public class ViewPagerAdapter extends RecyclerView.Adapter<ViewPagerAdapter.ViewHolder> {
private List<Integer> colors;
ViewPagerAdapter(List<Integer> colors){
this.colors = colors;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
int i = position % 4;
holder.titleTv.setText("item " + i);
holder.container.setBackgroundColor(colors.get(i));
}
@Override
public int getItemCount() {
//实现无限轮播
return Integer.MAX_VALUE;
}
class ViewHolder extends RecyclerView.ViewHolder{
RelativeLayout container;
TextView titleTv;
public ViewHolder(@NonNull View itemView) {
super(itemView);
container = itemView.findViewById(R.id.container);
titleTv = itemView.findViewById(R.id.tv_title);
}
}
}
4.绘制指示点
绘制一个白色的点和一个蓝色的点用于指示。
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <size android:width="8dp" android:height="8dp"/> <corners android:radius="8dp"/> <solid android:color="#ffffff"/> </shape>
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <size android:width="8dp" android:height="8dp"/> <corners android:radius="8dp"/> <solid android:color="#00ccff"/> </shape>
5.实现
public class MainActivity extends AppCompatActivity {
private ViewPager2 viewPager2;
private int lastPosition; //记录轮播图最后所在的位置
private List<Integer> colors = new ArrayList<>(); //轮播图的颜色
private LinearLayout indicatorContainer; //填充指示点的容器
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化组件
viewPager2 = findViewById(R.id.viewpager2);
indicatorContainer = findViewById(R.id.container_indicator);
initColors();
//初始化指示点
initIndicatorDots();
//添加适配器
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(colors);
viewPager2.setAdapter(viewPagerAdapter);
//设置轮播图初始位置在500,以保证可以手动前翻
viewPager2.setCurrentItem(500);
//最后所在的位置设置为500
lastPosition = 500;
//注册轮播图的滚动事件监听器
viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
super.onPageSelected(position);
//轮播时,改变指示点
int current = position % 4;
int last = lastPosition % 4;
indicatorContainer.getChildAt(current).setBackgroundResource(R.drawable.shape_dot_selected);
indicatorContainer.getChildAt(last).setBackgroundResource(R.drawable.shape_dot);
lastPosition = position;
}
});
}
private void initColors(){
colors.add(Color.BLUE);
colors.add(Color.YELLOW);
colors.add(Color.GREEN);
colors.add(Color.RED);
}
/**
* 初始化指示点
*/
private void initIndicatorDots(){
for(int i = 0; i < colors.size(); i++){
ImageView imageView = new ImageView(this);
if (i == 0) imageView.setBackgroundResource(R.drawable.shape_dot_selected);
else imageView.setBackgroundResource(R.drawable.shape_dot);
//为指示点添加间距
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMarginEnd(4);
imageView.setLayoutParams(layoutParams);
//将指示点添加进容器
indicatorContainer.addView(imageView);
}
}
/* 当应用被唤醒时,让轮播图开始轮播 */
@Override
protected void onResume() {
super.onResume();
mHandler.postDelayed(runnable,5000);
}
/* 当应用被暂停时,让轮播图停止轮播 */
@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacks(runnable);
} private final Runnable runnable = new Runnable() {
@Override
public void run() {
//获得轮播图当前的位置
int currentPosition = viewPager2.getCurrentItem();
currentPosition++;
viewPager2.setCurrentItem(currentPosition,true);
mHandler.postDelayed(runnable,5000);
}
};
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)