android輪播圖組件的制作方法

本文實例為大傢分享瞭android輪播圖組件的制作方法,供大傢參考,具體內容如下

BannerLayout

package com.coral3.common_module.components;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.coral3.common_module.R;
import com.coral3.common_module.utils.LogUtil;
import com.coral3.common_module.viewPager.ChildViewPager;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class BannerLayout extends LinearLayout {

    private Context mContext;
    private View view;
    private ChildViewPager viewPager;
    private ImageView indicator;
    private ImageView[] indicators;
    private Boolean isContinue = true;
    private ViewGroup group;
    private AtomicInteger index = new AtomicInteger();
    private Handler handler = new Handler(new Handler.Callback(){

        @Override
        public boolean handleMessage(Message message) {
            viewPager.setCurrentItem(message.what);
            return false;
        }
    });

    public BannerLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        initView();
        initListener();
    }

    private void initView(){
        view = LayoutInflater.from(mContext).inflate(R.layout.layout_banner, this);
        group = view.findViewById(R.id.view_indicators);
        viewPager = view.findViewById(R.id.view_banners);
        // 動態加入圖片
        List<View> listPics = new ArrayList<>();
        ImageView img1 = new ImageView(mContext);
        img1.setBackgroundResource(R.drawable.banner1);
        listPics.add(img1);
        ImageView img2 = new ImageView(mContext);
        img2.setBackgroundResource(R.drawable.banner2);
        listPics.add(img2);
        ImageView img3 = new ImageView(mContext);
        img3.setBackgroundResource(R.drawable.banner3);
        listPics.add(img3);
        ImageView img4 = new ImageView(mContext);
        img4.setBackgroundResource(R.drawable.banner4);
        listPics.add(img4);
        ImageView img5 = new ImageView(mContext);
        img5.setBackgroundResource(R.drawable.banner4);
        listPics.add(0, img5);
        ImageView img0 = new ImageView(mContext);
        img0.setBackgroundResource(R.drawable.banner1);
        listPics.add(img0);
        //動態加入指示器
        indicators = new ImageView[listPics.size()];
        for(int i = 0; i < indicators.length; i++){
            indicator = new ImageView(mContext);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(15, 15);
            layoutParams.setMargins(0, 0, 10, 0);
            indicator.setLayoutParams(layoutParams);
            indicators[i] = indicator;
            if(i == 1){
                indicators[i].setBackgroundResource(R.drawable.shape_banner_checked);
            }else{
                indicators[i].setBackgroundResource(R.drawable.shape_banner_unchecked);
            }
            if(i == 0 || i == 5){
                indicators[i].setVisibility(View.INVISIBLE);
            }
            group.addView(indicators[i]);
        }
        viewPager.setAdapter(new MyPagerAdapter(listPics));
        index.incrementAndGet();
        // 輪播
        new Thread(new Runnable() {

            @Override
            public void run() {
                while (true){
                    if(isContinue){
                        handler.sendEmptyMessage(index.get());
                        whatOption();
                    }
                }
            }
        }).start();
    }

    private void initListener(){
        // 設置監聽器
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                LogUtil.d(positionOffset + "-" + positionOffsetPixels);
                // 無縫滾動均滑
//                if(positionOffset == 0.0){
//                    LogUtil.d(position + "");
//                    if(position == 5) {
//                        viewPager.setCurrentItem(1, false);
//                    }
//                    if(position == 0) {
//                        viewPager.setCurrentItem(4, false);
//                    }
//                }
            }

            @Override
            public void onPageSelected(int position) {
                index.getAndSet(position);
                if(position == 5) {
                    viewPager.setCurrentItem(1, false);
                }
                if(position == 0) {
                    viewPager.setCurrentItem(4, false);
                }
                for(int i = 0; i < indicators.length; i++){
                    if(i == index.get()){
                        indicators[i].setBackgroundResource(R.drawable.shape_banner_checked);
                    }else{
                        indicators[i].setBackgroundResource(R.drawable.shape_banner_unchecked);
                    }
                }
                if(position == 0) indicators[4].setBackgroundResource(R.drawable.shape_banner_checked);
                if(position == 5) indicators[1].setBackgroundResource(R.drawable.shape_banner_checked);
            }

            @Override
            public void onPageScrollStateChanged(int state) {}
        });
        // 設置觸摸時停止定時
        viewPager.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        isContinue = false;
                        break;
                    case MotionEvent.ACTION_UP:
                        isContinue = true;
                        break;
                }
                return false;
            }
        });
    }

    class MyPagerAdapter extends PagerAdapter {

        private List<View> listView;

        @Override
        public int getCount() {
            return listView.size();
        }

        public MyPagerAdapter(List<View> listView){
            this.listView = listView;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            container.addView(listView.get(position));
            return listView.get(position);
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView(listView.get(position));
        }
    }

    private void whatOption(){
        index.incrementAndGet();
        if(index.get() > indicators.length - 2){
            index.getAndAdd(-4);
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

layout_banner

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <com.coral3.common_module.viewPager.ChildViewPager
            android:id="@+id/view_banners"
            android:layout_width="match_parent"
            android:layout_height="200dp"/>
        <LinearLayout
            android:id="@+id/view_indicators"
            android:layout_below="@+id/view_banners"
            android:gravity="center"
            android:layout_marginTop="-15dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" />
    </RelativeLayout>
</LinearLayout>

ChildViewPager

package com.coral3.common_module.viewPager;

import android.content.Context;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.viewpager.widget.ViewPager;

public class ChildViewPager extends ViewPager {
    /** 觸摸時按下的點 **/
    PointF downP = new PointF();
    /** 觸摸時當前的點 **/
    PointF curP = new PointF();
    public ChildViewPager(Context context) {
        super(context);
    }

    public ChildViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private static final String TAG = "ChildViewpager";
    @Override
    public boolean onTouchEvent(MotionEvent arg0) {
        //每次進行onTouch事件都記錄當前的按下的坐標
        if(getChildCount()<=1)
        {
            return super.onTouchEvent(arg0);
        }
        curP.x = arg0.getX();
        curP.y = arg0.getY();

        if(arg0.getAction() == MotionEvent.ACTION_DOWN)
        {

            //記錄按下時候的坐標
            //切記不可用 downP = curP ,這樣在改變curP的時候,downP也會改變
            downP.x = arg0.getX();
            downP.y = arg0.getY();
            //此句代碼是為瞭通知他的父ViewPager現在進行的是本控件的操作,不要對我的操作進行幹擾
            getParent().requestDisallowInterceptTouchEvent(true);
        }

        if(arg0.getAction() == MotionEvent.ACTION_MOVE){
            //此句代碼是為瞭通知他的父ViewPager現在進行的是本控件的操作,不要對我的操作進行幹擾
            getParent().requestDisallowInterceptTouchEvent(true);
        }

        if(arg0.getAction() == MotionEvent.ACTION_UP || arg0.getAction() == MotionEvent.ACTION_CANCEL){
            //在up時判斷是否按下和松手的坐標為一個點
            //如果是一個點,將執行點擊事件,這是我自己寫的點擊事件,而不是onclick
            getParent().requestDisallowInterceptTouchEvent(false);
            if(downP.x==curP.x && downP.y==curP.y){
                return true;
            }
        }
        super.onTouchEvent(arg0); //註意這句不能 return super.onTouchEvent(arg0); 否則觸發parent滑動
        return true;
    }
}

使用

<com.coral3.common_module.components.BannerLayout
            android:id="@+id/home_banner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: