轮播图学习2:实现轮播图自动跳转

要实现轮播图自动跳转 需要自己写一个类ScoViewParger继承ViewParger,将activity_mian.xml文件中关于ViewRarger的布局改写成为包名+类名的方式

ScoViewParger类:
package com.example.myapplication23;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;


import java.util.logging.LogRecord;

public class ScoViewParger extends ViewPager {
    private Handler handler;
    public ScoViewParger(@NonNull Context context) {
        this(context,null);
    }

    public ScoViewParger(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        handler=new Handler(Looper.getMainLooper());



    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        startLooper();
    }
    private void startLooper(){
        handler.postDelayed(mTask,5000);
    }
    private Runnable mTask=new Runnable() {
        @Override
        public void run() {
            int currentItem=getCurrentItem();
            currentItem++;
            setCurrentItem(currentItem);
            postDelayed(this,5000);
        }
    };
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopLooper();
    }
    private void stopLooper(){
        handler.removeCallbacks(mTask);
    }
}

activity_mian.xml

<?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:tools="http://schemas.android.com/tools"
    tools:content=".MainActivity">

    <com.example.myapplication23.ScoViewParger
        android:id="@+id/im1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"/>


</RelativeLayout>

其他部分同上一篇博客

原文地址:https://www.cnblogs.com/wangzhaojun1670/p/12769661.html