【Recycleview滑动】Recycleview+snapHelper实现列表联动

实现双列表联动(仿网页PC端选择)

一篇小文章

直接上图点击下方各项可以切换,滑动上方卡片也可以联动下方的各项
主要实现方法:
1)上方卡片滑动监听处理代码:

    mRecycleview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

				//recycleView中获取显示item的位置
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) recyclerView.getChildAt(0).getLayoutParams();
                int viewAdapterPosition = layoutParams.getViewAdapterPosition();
                //根据当前位置设置下方recycleView的位置
                recycleviewHint.smoothScrollToPosition(viewAdapterPosition);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

下方列表点击事件处理:

        hintAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mRecycleview.scrollToPosition(i);
                recycleviewHint.smoothScrollToPosition(i);
            }
        });

点击下方列表,当前item显示在中间关键代码需要改造LinearLayoutManager
感谢电动小马达的分享[RecyclerView 列表点击定位到中间位置]sn(https://blog.csdn.net/weixin_42046829/article/details/110053790)


public class CenterLayoutManager extends LinearLayoutManager {

    public CenterLayoutManager(Context context) {
        super(context);
    }

    public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        LinearSmoothScroller smoothScroller =
                new CenterSmoothScroller(recyclerView.getContext()) {
                    // 返回:滑过1px时经历的时间(ms)。
                    @Override
                    protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                        return 150f / displayMetrics.densityDpi;
                    }
                };

        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }


    private static class CenterSmoothScroller extends LinearSmoothScroller {

        CenterSmoothScroller(Context context) {
            super(context);
        }

        @Override
        public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
            return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
        }
    }
}

布局代码activity_main.xml

// An highlighted block
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleview"
        android:layout_width="match_parent"
        android:layout_height="400dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingStart="10dp"
        android:paddingEnd="10dp">

        <TextView
            android:id="@+id/tvHead"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="head"
            android:textColor="#000"
            android:textSize="18sp" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycleviewHint"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/tvFoot"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:padding="10dp"
            android:text="foot"
            android:textColor="#000"
            android:textSize="18sp" />
    </LinearLayout>
</LinearLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardUseCompatPadding="true"
    app:cardPreventCornerOverlap="true"
    app:cardElevation="6dp"
    app:cardCornerRadius="5dp"
    android:clickable="true"
    android:foreground="?attr/selectableItemBackground"
    android:layout_marginStart="30dp"
    android:layout_marginTop="30dp"
    android:layout_marginEnd="30dp"
    android:layout_marginBottom="30dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="match_parent">
        <ImageView
            android:layout_width="match_parent"
            android:layout_weight="7"
            android:scaleType="fitXY"
            android:id="@+id/img"
            android:background="@mipmap/a1"
            android:layout_height="0dp" />
        <TextView
            android:layout_width="match_parent"
            android:layout_weight="3"
            android:id="@+id/tv"
            android:padding="5dp"
            android:text="no.1"
            android:layout_height="0dp" />
    </LinearLayout>
</android.support.v7.widget.CardView>

item_rv_hint.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:foreground="?attr/selectableItemBackground">

    <TextView
        android:id="@+id/tv"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp"
        android:textSize="18sp"
        android:textColor="#000"
        android:text="1" />
</LinearLayout>

MenuActivity.class


import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecycleview;
    private BaseQuickAdapter<TestBean, BaseViewHolder> mBaseQuickAdapter;
    private BaseQuickAdapter hintAdapter;
    private ArrayList<TestBean> mDatas;
    private RecyclerView recycleviewHint;
    private ArrayList<TestBean> hintDatas = new ArrayList<>();
    private int[] imgs = {R.mipmap.a1, R.mipmap.a2, R.mipmap.a3, R.mipmap.a4, R.mipmap.a5, R.mipmap.a6, R.mipmap.a1, R.mipmap.a2, R.mipmap.a3, R.mipmap.a4, R.mipmap.a5, R.mipmap.a6};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecycleview = (RecyclerView) findViewById(R.id.recycleview);
        recycleviewHint = (RecyclerView) findViewById(R.id.recycleviewHint);
        final TextView tvHead = (TextView) findViewById(R.id.tvHead);
        final TextView tvFoot = (TextView) findViewById(R.id.tvFoot);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecycleview.setLayoutManager(linearLayoutManager);
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(mRecycleview);
        mDatas = new ArrayList<>();
        for (int x = 0; x < imgs.length; x++) {
            TestBean testBean = new TestBean();
            testBean.setText("this is No." + (x + 1));
            testBean.setImgs(imgs[x]);
            mDatas.add(testBean);
            hintDatas.add(new TestBean((x + 1) + ""));
        }

        mBaseQuickAdapter = new BaseQuickAdapter<TestBean, BaseViewHolder>(R.layout.item, mDatas) {
            @Override
            protected void convert(BaseViewHolder helper, TestBean item) {
                ImageView img = helper.getView(R.id.img);
                final TextView tv = helper.getView(R.id.tv);
                img.setImageResource(item.getImgs());
                tv.setText(item.getText());
                Palette.from(BitmapFactory.decodeResource(getResources(), item.getImgs())).generate(new Palette.PaletteAsyncListener() {
                    @Override
                    public void onGenerated(Palette palette) {
                        int vibrantColor = palette.getVibrantColor(Color.BLUE);
                        tv.setTextColor(vibrantColor);
                    }
                });
            }
        };
        mRecycleview.setAdapter(mBaseQuickAdapter);
        mRecycleview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) recyclerView.getChildAt(0).getLayoutParams();
                int viewAdapterPosition = layoutParams.getViewAdapterPosition();
                recycleviewHint.smoothScrollToPosition(viewAdapterPosition);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        final LinearLayoutManager centerLayoutManager = new CenterLayoutManager(this);
        centerLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        hintAdapter = new BaseQuickAdapter<TestBean, BaseViewHolder>(R.layout.item_rv_hint, hintDatas) {
            @Override
            protected void convert(BaseViewHolder helper, TestBean item) {
                final TextView tv = helper.getView(R.id.tv);
                tv.setText(item.getText());
            }
        };
        recycleviewHint.setLayoutManager(centerLayoutManager);
        recycleviewHint.setAdapter(hintAdapter);

        hintAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                mRecycleview.scrollToPosition(i);
                recycleviewHint.smoothScrollToPosition(i);
            }
        });
        tvHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRecycleview.scrollToPosition(0);
                recycleviewHint.scrollToPosition(0);
            }
        });
        tvFoot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRecycleview.scrollToPosition(mDatas.size() - 1);
                recycleviewHint.scrollToPosition(hintDatas.size() - 1);
            }
        });
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值