0.先放上效果图看看是不是你想要的效果
在这里插入图片描述

1.添加依赖

dependencies {
    ...
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}

2.主页面布局activity_main2

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication001.MainActivity2">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="250dp"&gt;
    </androidx.viewpager2.widget.ViewPager2>

    <LinearLayout
        android:orientation="vertical"
        android:gravity="center"
        android:background="#66000000"
        android:layout_alignBottom="@id/vp"
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <TextView
            android:id="@+id/desc"
            android:text="描述文本"
            android:textColor="#ffffff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <LinearLayout
            android:id="@+id/layout_dot"
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

3.主页面活动MainActivity2


import androidx.annotation.Px;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity2 extends AppCompatActivity {

    private String[] descs = {"为梦想坚持", "我相信我是黑马", "黑马公开课", "Google/IO", "轻松1w+"};
    private ViewPager2 viewPager2;
    private TextView tv_desc;//描述文本
    private LinearLayout layout_dot;//指示器布局容器
    private List<Integer> colors = new ArrayList<>();   //轮播图的颜色
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        //初始化控件
        viewPager2 = (ViewPager2) findViewById(R.id.vp);
        tv_desc = (TextView) findViewById(R.id.desc);
        layout_dot = (LinearLayout) findViewById(R.id.layout_dot);
        //初始化颜色
        initColors();
        //初始化文字下方的点
        initDot();

        //添加适配
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(colors);
        viewPager2.setAdapter(viewPagerAdapter);
        //设置轮播图初始位置在500000000,以保证可以手动前翻,实现无限轮播,实际上当滑到0时,就不可以在左滑,所以需要设置很大的数字,来实现无限轮播
        viewPager2.setCurrentItem(500000000);
        //注册轮播图的滚动事件监听
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

            //当页面滚动触发时间
            public void onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels) {

            }

            //当页面被选中触发方法
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                int current = position % 5;//有多少个页面就写多少,这里有5种颜色就写5,除以5取余
                //当页面被选中的时候,改变描述文本
                tv_desc.setText(descs[current]);
                //当页面被选中的时候,改变指示点
                changeDots(current);
            }

            public void onPageScrollStateChanged(@ViewPager2.ScrollState int state) {
                //当页面空闲状态被改变的时候
                if (state == viewPager2.SCROLL_STATE_IDLE) {
                    mHandler.postDelayed(runnable,5000);//延时5秒,自动轮播图片
                    Log.v("22222",  "页面空闲状态");
                } else {
                    Log.v("22222",  "页面空闲状态被改变");
                    mHandler.removeCallbacks(runnable);//用户手指触摸页面,停止自动轮播图片
                }
            }
        });
    }

    //初始化颜色
    private void initColors(){
        colors.add(Color.BLUE);
        colors.add(Color.YELLOW);
        colors.add(Color.GREEN);
        colors.add(Color.RED);
        colors.add(Color.DKGRAY);
    }

    //初始化文字下方的点
    private void initDot() {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(10, 10);
        layoutParams.setMargins(4, 4, 4, 4);
        for (int i = 0; i < colors.size(); i++) {
            View view = new View(this);
            view.setBackgroundResource(R.drawable.seletor_dot);
            view.setLayoutParams(layoutParams);
            if(i==0){//初始化后第一个点设置为红色
                view.setSelected(true);
            }
            layout_dot.addView(view);
        }
        Log.v("1212",  "打印layout_dot.getChildCount()= "+layout_dot.getChildCount());
        Log.v("1212",  "打印colors.size()= "+colors.size());
    }

    /**
     * 自动轮播图方法实现无限轮播
     */
    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //获得轮播图当前位置
            int currentPosition = viewPager2.getCurrentItem();
            currentPosition++;
            viewPager2.setCurrentItem(currentPosition,true);
            mHandler.postDelayed(runnable,5000);//延时5秒,自动轮播图片
        }
    };

    //选中对应的原点
    private void changeDots(int position) {
        Log.v("11111",  "打印layout_dot.getChildCount()= "+layout_dot.getChildCount());
        //先把所有的点恢复为白色
        for (int i = 0; i < layout_dot.getChildCount(); i++) {
            View view = layout_dot.getChildAt(i);
            view.setSelected(false);
        }
        //获取当前被选中的条目 设置为选中状态
        layout_dot.getChildAt(position).setSelected(true);
    }

    /* 当应用唤醒时,让轮播图开始轮播 */
    @Override
    protected void onResume() {
        super.onResume();
        mHandler.postDelayed(runnable,5000);//延时5秒,自动轮播图片
        Log.v("22222",  "当应用唤醒时,让轮播图开始轮播 ");
    }

    /* 当应用被暂停时,让轮播图停止轮播 */
    @Override
    protected void onPause() {
        super.onPause();
        mHandler.removeCallbacks(runnable);
        Log.v("22222",  "当应用被暂停时,让轮播图停止轮播 ");
    }

}

4.绘制指示点的背景文件drawable文件下的seletor_dot文件,有两种颜色,白色和红色

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/shape_point_selector" android:state_selected="true" />
    <item android:drawable="@drawable/shape_point_normal" android:state_selected="false"/>

</selector>

5.drawable文件夹下的shape_point_selector

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <size
        android:width="40dp"
        android:height="40dp"
        />
    <solid android:color="#ff4400"/>

</shape>

6.drawable文件夹下的shape_point_normal

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval"
    >
    <size
        android:width="40dp"
        android:height="40dp"
        />
    <solid android:color="#dfdfdf"/>

</shape>

7.ViewPager2的适配器ViewPagerAdapter,用法和RecyclerView适配器类似。ViewPagerAdapter类对象

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

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.recycleview_item,parent,false));
    }

    //绑定数据
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        int i = position % 5;//有多少个页面就写多少,这里有5种颜色就写5,除以5取余数
        holder.titleTv.setText("第" + 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);
        }
    }
}

8.适配器ViewPagerAdapter的布局recycleview_item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    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>

原文地址:https://blog.csdn.net/qq_36570506/article/details/128425673

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_17355.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注