Android 仿探探左右滑动(简单搭建)

需求防探探左右滑动 基本框架

使用RecycleView实现左右滑动,自定义RecycleView的ItemDecoration实现
GalleryItemDecoration 为自定义的ItemDecoration


package com.chaochaow.weather.widget;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import androidx.recyclerview.widget.RecyclerView;


public class GalleryItemDecoration extends RecyclerView.ItemDecoration {

    int mPageMargin = 15;//自定义默认item边距
    int mLeftPageVisibleWidth;//第一张图片的左边距

    public GalleryItemDecoration(Context context) {
        WindowManager manager = ((Activity) context).getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        mLeftPageVisibleWidth = (int) (((width / Resources.getSystem().getDisplayMetrics().density) - mPageMargin) / 2);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int positon = parent.getChildAdapterPosition(view); //获得当前item的position
        int itemCount = parent.getAdapter().getItemCount(); //获得item的数量
        int leftMargin;
        if (positon == 0) {
            leftMargin = dpToPx(mPageMargin);
        } else {
            leftMargin = dpToPx(mPageMargin);
        }
        int rightMargin;
        if (positon == itemCount - 1) {
            rightMargin = dpToPx(mPageMargin);
        } else {
            rightMargin = dpToPx(mPageMargin);
        }
        RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) view.getLayoutParams();
        lp.setMargins(leftMargin, 20, rightMargin, 0);
        view.setLayoutParams(lp);
        super.getItemOffsets(outRect, view, parent, state);
    }

    private int dpToPx(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density + 0.5f); //dp转px
    }
}

直接在Activity中的Recyclew使用 Activiry关键代码如下,适配器item样式可以随便放一张图片以达到效果就行 具体样式根据需求修改

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecycle.setLayoutManager(layoutManager);
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(mRecycle);
        GalleryItemDecoration decoration = new GalleryItemDecoration(getActivity());
        mRecycle.addItemDecoration(decoration);
        mRecycle.setAdapter(mAdapter);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值