欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 自定义无限轮播

程序员文章站 2022-07-10 18:50:54
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录自定义无限轮播前言根据项目需求写的无限自动填充的轮播控件提示:以下是本篇文章正文内容,下面案例可供参考一、效果二、使用步骤1.引入库代码如下(示例):单个名片package com.dtstar.mobile.ui.home.view;import android.content.Context;import android.support.constraint.Const.....

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

 

文章目录

自定义无限轮播

 


前言

根据项目需求写的无限自动填充的轮播控件


提示:以下是本篇文章正文内容,下面案例可供参考

一、效果

Android 自定义无限轮播

二、使用步骤

1.引入库

代码如下(示例):单个名片

package com.dtstar.mobile.ui.home.view;

import android.content.Context;
import android.support.constraint.ConstraintLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dtstar.core.bean.HomeHotRoom;
import com.dtstar.framework.util.util.DisplayUtils;
import com.dtstar.mobile.ChatApplicationLike;
import com.dtstar.mobile.R;
import com.dtstar.mobile.room.RoomFrameActivity;
import com.dtstar.mobile.ui.home.adpater.YYHomeAdapter;
import com.dtstar.mobile.ui.home.dialog.YYHomeDialog;
import com.dtstar.mobile.utils.ImageLoadUtils;
import com.juxiao.library_utils.log.LogUtil;

import static com.netease.nim.uikit.common.util.sys.ScreenUtil.screenWidth;

public class RecommendCardView extends ConstraintLayout {

    private ImageView ivAvatar, ivLabel, ivFrame, ivSupportlabel;
    private TextView tvRedu, tvInformation;
    private int imgWidth, imgHeight;

    public RecommendCardView(Context context) {
        super(context);
        init();
    }

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

    public RecommendCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View view = inflate(getContext(), R.layout.card_layout, this);
        ivAvatar = view.findViewById(R.id.iv_avatar);
        ivLabel = view.findViewById(R.id.iv_label);
        ivFrame = view.findViewById(R.id.iv_frame);
        ivSupportlabel = view.findViewById(R.id.iv_supportlabel);
        tvRedu = view.findViewById(R.id.tv_redu);
        tvInformation = view.findViewById(R.id.tv_information);
        ConstraintLayout constraintlayout = view.findViewById(R.id.constraintlayout);

        int screenWidth = DisplayUtils.getScreenWidth(getContext());

        imgWidth = (screenWidth - DisplayUtils.dip2px(getContext(), 30)) / 3;
        imgHeight = imgWidth + DisplayUtils.dip2px(getContext(), 23);
        ViewGroup.LayoutParams params = constraintlayout.getLayoutParams();
        params.width = imgWidth;
        params.height = imgHeight;
        constraintlayout.setLayoutParams(params);

        ViewGroup.LayoutParams avatarParams = ivAvatar.getLayoutParams();
        avatarParams.width = imgWidth;
        avatarParams.height = imgWidth;
        ivAvatar.setLayoutParams(avatarParams);

        ViewGroup.LayoutParams frameParams = ivFrame.getLayoutParams();
        frameParams.width = imgWidth;
        frameParams.height = imgWidth;
        ivFrame.setLayoutParams(frameParams);

    }

    /**
     * 设置头像网络图片url
     */
    public void setIvAvatarUrl(String url) {
        ImageLoadUtils.loadImageWidthHeight(getContext(), url, ivAvatar, imgWidth, imgWidth);
    }

    /**
     * 设置头像本地资源图片ID
     */
    public void setIvAvatarID(int imgId) {
        ivAvatar.setImageResource(imgId);
    }

    /**
     * 设置房间标签网络图片url
     */
    public void setIvLabelUrl(String url) {
        ImageLoadUtils.loadImage(getContext(), url, ivLabel);
    }

    /**
     * 设置房间标签本地资源图片ID
     */
    public void setIvLabelID(int imgId) {
        ivLabel.setImageResource(imgId);
    }

    /**
     * 设置房间热度
     */
    public void setTvRedu(String str) {
        tvRedu.setText(str);
    }

    /**
     * 设置房间热度的显示与隐藏
     */
    public void setTvReduVisibility(int visibility) {
        tvRedu.setVisibility(visibility);
    }

    /**
     * 设置房间标题
     */
    public void setTvInformation(String str) {
        tvInformation.setText(str);
    }

    /**
     * 设置边框
     */
    public void setIvFrame(String url) {
        ImageLoadUtils.loadImageWidthHeight(getContext(), url, ivFrame, imgWidth, imgWidth);
    }

    /**
     * 设置助力标签
     */
    public void setIvSupportlabel(String url) {
        ImageLoadUtils.loadImage(getContext(), url, ivSupportlabel);
    }

    /**
     * 设置点击事件
     */
    public void setOnItemClickListener(OnRecommendClickListener listener) {
        mClickListener = listener;
    }

    public interface OnRecommendClickListener {
        void onRecommendClick();
    }

    private OnRecommendClickListener mClickListener;

    @Override
    protected void onAttachedToWindow() {
//        LogUtil.e("oomTest : ", "RecommendCardView onViewAdded " + ChatApplicationLike.addRecommendCardViewCount());
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
//        LogUtil.e("oomTest : ", "RecommendCardView onViewRemoved" + ChatApplicationLike.subRecommendCardViewCount());
        super.onDetachedFromWindow();
    }
}

一屏要展示的

package com.dtstar.mobile.ui.home.view;

import android.content.Context;
import android.opengl.Visibility;
import android.support.constraint.ConstraintLayout;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.dtstar.core.bean.HomeHotRoom;
import com.dtstar.mobile.ChatApplicationLike;
import com.dtstar.mobile.R;
import com.dtstar.mobile.room.RoomFrameActivity;
import com.dtstar.mobile.utils.ImageLoadUtils;
import com.dtstar.mobile.utils.UIHelper;
import com.juxiao.library_utils.log.LogUtil;

public class RecommendView extends ConstraintLayout {

    private RecommendCardView recommendcardview1,recommendcardview2,recommendcardview3;


    public RecommendView(Context context) {
        super(context);
        init(context);
    }

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

    public RecommendView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        View view = inflate(context, R.layout.item_layout_recommend,this);
        recommendcardview1 = (RecommendCardView) view.findViewById(R.id.recommendcardview1);
        recommendcardview2 = (RecommendCardView) view.findViewById(R.id.recommendcardview2);
        recommendcardview3 = (RecommendCardView) view.findViewById(R.id.recommendcardview3);
    }

    /**设置第一组数据*/
    public void setCardview1(HomeHotRoom homeHotRoom){
        if(!homeHotRoom.isBg()){
            recommendcardview1.setIvAvatarUrl(homeHotRoom.getAvatar());
            recommendcardview1.setIvLabelUrl(homeHotRoom.getTagPict());
            recommendcardview1.setTvRedu(String.valueOf(homeHotRoom.getDegree()));
            recommendcardview1.setTvReduVisibility(homeHotRoom.getDegree()==0 ? GONE : VISIBLE);
            if(homeHotRoom.getRecommTagPicUrl() != null && homeHotRoom.getRecommTagPicUrl().length() > 0){
                recommendcardview1.setIvFrame(homeHotRoom.getRecommTagPicUrl());
            }
            if(homeHotRoom.getBoostTagPic() != null && homeHotRoom.getBoostTagPic().length() > 0){
                recommendcardview1.setIvSupportlabel(homeHotRoom.getBoostTagPic());
            }
        }else{
            recommendcardview1.setIvAvatarID(R.mipmap.home_img_vacant_position);
        }
        recommendcardview1.setTvInformation( (homeHotRoom.getTitle() != null && homeHotRoom.getTitle().length() > 0) ? homeHotRoom.getTitle() : homeHotRoom.getNick() );
        recommendcardview1.setOnClickListener(v -> {
            if(homeHotRoom.isBg()){
                UIHelper.showRecommendedPositionH5(getContext());
            }else{
                RoomFrameActivity.start(getContext(), homeHotRoom.getUid(), homeHotRoom.getType());
            }
        });
        recommendcardview1.setVisibility(VISIBLE);
    }

    /**设置第二组数据*/
    public void setCardview2(HomeHotRoom homeHotRoom){
        if(!homeHotRoom.isBg()){
            recommendcardview2.setIvAvatarUrl(homeHotRoom.getAvatar());
            recommendcardview2.setIvLabelUrl(homeHotRoom.getTagPict());
            recommendcardview2.setTvRedu(String.valueOf(homeHotRoom.getDegree()));
            recommendcardview2.setTvReduVisibility(homeHotRoom.getDegree()==0 ? GONE : VISIBLE);
            if(homeHotRoom.getRecommTagPicUrl() != null && homeHotRoom.getRecommTagPicUrl().length() > 0){
                recommendcardview2.setIvFrame(homeHotRoom.getRecommTagPicUrl());
            }
            if(homeHotRoom.getBoostTagPic() != null && homeHotRoom.getBoostTagPic().length() > 0){
                recommendcardview2.setIvSupportlabel(homeHotRoom.getBoostTagPic());
            }
        }else{
            recommendcardview2.setIvAvatarID(R.mipmap.home_img_vacant_position);
        }
        recommendcardview2.setTvInformation( (homeHotRoom.getTitle() != null && homeHotRoom.getTitle().length() > 0) ? homeHotRoom.getTitle() : homeHotRoom.getNick() );
        recommendcardview2.setOnClickListener(v -> {
            if(homeHotRoom.isBg()){
                UIHelper.showRecommendedPositionH5(getContext());
            }else{
                RoomFrameActivity.start(getContext(), homeHotRoom.getUid(), homeHotRoom.getType());
            }
        });
        recommendcardview2.setVisibility(VISIBLE);
    }

    /**设置第三组数据*/
    public void setCardview3(HomeHotRoom homeHotRoom){
        if(!homeHotRoom.isBg()){
            recommendcardview3.setIvAvatarUrl(homeHotRoom.getAvatar());
            recommendcardview3.setIvLabelUrl(homeHotRoom.getTagPict());
            recommendcardview3.setTvRedu(String.valueOf(homeHotRoom.getDegree()));
            recommendcardview3.setTvReduVisibility(homeHotRoom.getDegree()==0 ? GONE : VISIBLE);
            if(homeHotRoom.getRecommTagPicUrl() != null && homeHotRoom.getRecommTagPicUrl().length() > 0){
                recommendcardview3.setIvFrame(homeHotRoom.getRecommTagPicUrl());
            }
            if(homeHotRoom.getBoostTagPic() != null && homeHotRoom.getBoostTagPic().length() > 0){
                recommendcardview3.setIvSupportlabel(homeHotRoom.getBoostTagPic());
            }
        }else{
            recommendcardview3.setIvAvatarID(R.mipmap.home_img_vacant_position);
        }
        recommendcardview3.setTvInformation( (homeHotRoom.getTitle() != null && homeHotRoom.getTitle().length() > 0) ? homeHotRoom.getTitle() : homeHotRoom.getNick() );
        recommendcardview3.setOnClickListener(v -> {
            if(homeHotRoom.isBg()){
                UIHelper.showRecommendedPositionH5(getContext());
            }else{
                RoomFrameActivity.start(getContext(), homeHotRoom.getUid(), homeHotRoom.getType());
            }
        });
        recommendcardview3.setVisibility(VISIBLE);
    }

    @Override
    protected void onAttachedToWindow() {
        //LogUtil.e("oomTest : ", "RecommendView onViewAdded " + ChatApplicationLike.addRecommendViewCount());
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        //LogUtil.e("oomTest : ", "RecommendView onViewRemoved" + ChatApplicationLike.subRecommendViewCount());
        super.onDetachedFromWindow();
    }
}

最后整体的动画及无限轮播填充的设置,(根据具体需求,可在这个文件中直接修改) 
package com.dtstar.mobile.ui.home.view;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.dtstar.core.bean.HomeHotRoom;
import com.dtstar.mobile.ChatApplicationLike;
import com.dtstar.mobile.R;
import com.juxiao.library_utils.log.LogUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class RecommendBannerView extends ConstraintLayout {

    private ViewPager viewPager;
    private LinearLayout linearLayout; //轮播指示器的,展示添加上不用,需要的时候在修改修改
    private List<HomeHotRoom> Hlist = new ArrayList<>();
    private boolean listSizeBoolean, isAutoPlay;
    private int screenWidth = 0; //获取屏幕宽度

    private RecommendAdapter recommendAdapter;

    private RecommendBannerHandler recommendBannerHandler = new RecommendBannerHandler(this);

    private static class RecommendBannerHandler extends Handler {
        private WeakReference<RecommendBannerView> weakReference;

        RecommendBannerHandler(RecommendBannerView recommendBannerView) {
            weakReference = new WeakReference<>(recommendBannerView);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    RecommendBannerView recommendBannerView = weakReference.get();
                    if (recommendBannerView != null) {
                        recommendBannerView.doPlay();
                    }
                    break;
            }
        }
    }

    private void doPlay() {
        int countItem = (viewPager.getCurrentItem() + 1);
        viewPager.setCurrentItem(countItem);
        sendPlay();
    }

    public RecommendBannerView(Context context) {
        super(context);
        init();
    }

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

    public RecommendBannerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View view = inflate(getContext(), R.layout.recommendbannerview_layout, this);
//        LogUtil.e("oomTest : RecommendBannerView init ");
        viewPager = view.findViewById(R.id.viewpager);
        linearLayout = view.findViewById(R.id.layout);
        ViewPagerTouchEvent();
    }

    public void setList(List<HomeHotRoom> Hlist) {
        if (this.Hlist.size() > 0) {
            this.Hlist.clear();
            if (recommendAdapter != null) {
                recommendAdapter.notifyDataSetChanged();
            }
        }
        this.Hlist.addAll(Hlist);
        if (this.Hlist.size() > 3) {
            listSizeBoolean = true;
            sendPlay();
        } else {
            listSizeBoolean = false;
            stopPlay();
        }
        recommendAdapter = null;
        viewPager.setAdapter(null);
        viewPager.removeAllViews();
        recommendAdapter = new RecommendAdapter();
        viewPager.setAdapter(recommendAdapter);
    }

    private class RecommendAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return listSizeBoolean ? Integer.MAX_VALUE : 1;
        }

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

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {

            RecommendView recommendView = new RecommendView(getContext());
            if (listSizeBoolean) {
                recommendView.setCardview1(Hlist.get(((position * 3) % Hlist.size())));
                recommendView.setCardview2(Hlist.get((((position * 3) + 1) % Hlist.size())));
                recommendView.setCardview3(Hlist.get((((position * 3) + 2) % Hlist.size())));
            } else {
                if (Hlist.size() == 1) {
                    recommendView.setCardview1(Hlist.get(((position * 3) % Hlist.size())));
                } else if (Hlist.size() == 2) {
                    recommendView.setCardview1(Hlist.get(((position * 3) % Hlist.size())));
                    recommendView.setCardview2(Hlist.get((((position * 3) + 1) % Hlist.size())));
                } else if (Hlist.size() == 3) {
                    recommendView.setCardview1(Hlist.get(((position * 3) % Hlist.size())));
                    recommendView.setCardview2(Hlist.get((((position * 3) + 1) % Hlist.size())));
                    recommendView.setCardview3(Hlist.get((((position * 3) + 2) % Hlist.size())));
                }
            }

            container.addView(recommendView);
            return recommendView;
        }

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

    private void ViewPagerTouchEvent() {
        viewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //当时MotionEvent.ACTION_DOWN和ACTION_MOVE,就移除handler发送的message.removeMessages.333
                        stopPlay();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        stopPlay();
                        break;
                    //当用户手松开时ACTION_UP,就继续使用sendEmptyMessageDelayed发送handler的消息.333
                    case MotionEvent.ACTION_UP:
                        sendPlay();
                    default:
                        break;
                }
                return false;
            }
        });
    }

//    @Override
//    public void onViewAdded(View view) {
//        LogUtil.e("oomTest : ", "RecommendBannerView onViewAdded " + ChatApplicationLike.addRecommendBannerCount());
//        super.onViewAdded(view);
//    }
//
//    @Override
//    public void onViewRemoved(View view) {
//        LogUtil.e("oomTest : ", "RecommendBannerView onViewRemoved" + ChatApplicationLike.subRecommendBannerCount());
//        super.onViewRemoved(view);
//    }

    @Override
    protected void onAttachedToWindow() {
//        LogUtil.e("oomTest : ", "RecommendBannerView onViewAdded " + ChatApplicationLike.addRecommendBannerCount());
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
//        LogUtil.e("oomTest : ", "RecommendBannerView onViewRemoved" + ChatApplicationLike.subRecommendBannerCount());
        onDestroy();
        super.onDetachedFromWindow();
    }

    private void sendPlay() {
        if (listSizeBoolean && isAutoPlay && recommendBannerHandler != null) {
            recommendBannerHandler.removeCallbacksAndMessages(null);
            recommendBannerHandler.sendEmptyMessageDelayed(1, 10000);
        }
    }

    private void stopPlay() {
        if (recommendBannerHandler != null) {
            recommendBannerHandler.removeCallbacksAndMessages(null);
        }
    }

    public void setAutoPlay(boolean isPlay) {
        this.isAutoPlay = isPlay;
    }

    public void onAutoPlay() {
        isAutoPlay = true;
        sendPlay();
    }

    public void onPausePlay() {
        isAutoPlay = false;
        stopPlay();
    }

    public void onDestroy() {
        isAutoPlay = false;
        stopPlay();
        recommendBannerHandler = null;
        if (viewPager != null) {
            viewPager.setOnTouchListener(null);
        }
    }
}

总结

自己做个记录,下次遇到类似需求,直接修改修改

本文地址:https://blog.csdn.net/qq_34165238/article/details/108854128