一、activity_main.xml布局文件:
<androidx.viewpager2.widget.ViewPager2 android:id="@+id/viewpager2" android:layout_width="403dp" android:layout_height="442dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <LinearLayout android:layout_width="397dp" android:layout_height="40dp" android:background="#66000000" android:gravity="center" android:orientation="vertical" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/viewpager2" app:layout_constraintVertical_bias="0.686"> <LinearLayout android:id="@+id/layout_dot" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="horizontal"> </LinearLayout> </LinearLayout>
二、MainActivity.java:
三、Adapter:
private int[] images= new int[]{R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four};
public ViewPager2Adapter(Context context, List<String> data, ViewPager2 viewPager2) {
this.mInflater = LayoutInflater.from(context);
this.list = data;
this.viewPager2 = viewPager2;
}
@NonNull
@Override
public ViewPager2Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.view_item, parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewPager2Adapter.ViewHolder holder, int position) {
holder.viewImage.setImageResource(images[position]);
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
RelativeLayout relativeLayout;
ImageView viewImage;
ViewHolder(View itemView) {
super(itemView);
viewImage = itemView.findViewById(R.id.imageView);
relativeLayout = itemView.findViewById(R.id.container);
}
}
四、运行效果:
五、项目工程: