android二级联动简书,笔记:Android二级联动---RecyclerView实现

做笔记免得以后有重写一边或者忘了,仅供自己学习(只实现功能,无动画实现,左边没做可见处理,有空再做吧):

1、左右两个RecyclerView,

2、左边RecyclerView点击某个item同时item改变背景颜色,右边RecyclerView置顶相对应的item

3、右边RecyclerView滑动,左边RecyclerView相对应的item被选中并且改变颜色

image.png

1、MainActivity.java中使用

package com.myapplication;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.LinearLayoutManager;

import android.support.v7.widget.RecyclerView;

import android.view.View;

import java.util.ArrayList;

import java.util.List;

public class MainActivity extends AppCompatActivity {

private isScroll=false;

private RecyclerView rv_left_classify;

private RecyclerView rv_right_classify;

private List dataList;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

rv_left_classify= (RecyclerView) findViewById(R.id.rv_left_classify);//左边recyclerview

rv_right_classify= (RecyclerView) findViewById(R.id.rv_right_classify);//右边recyclerview

initViewAndData();

}

public void initViewAndData() {

dataList=new ArrayList<>();

for (int i=0;i<20;i++){

dataList.add("数据第"+i+"条");

}

//右边recyclerview

//这个是自定义后的LayoutManager

final RecyclerView.LayoutManager layoutManagerRight=new AdvertiseLinearLayoutManager(this, LinearLayoutManager.VERTICAL,false);

rv_right_classify.setLayoutManager(layoutManagerRight);

ClassifyRVRightAdapter classifyAdapterRight=new ClassifyRVRightAdapter(this,dataList);

rv_right_classify.setAdapter(classifyAdapterRight);

//左边recyclerview

RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);

rv_left_classify.setLayoutManager(layoutManager);

final ClassifyRVLeftAdapter classifyRVAdapterLeft=new ClassifyRVLeftAdapter(this,dataList);

rv_left_classify.setAdapter(classifyRVAdapterLeft);

//右边recyclerview

//右边recyclerview在滚动的时候监听第一个可见或者最后可见的item,这里是利用LayoutManager才可以监听到的

rv_right_classify.setOnScrollListener(new RecyclerView.OnScrollListener() {

@Override

public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

super.onScrolled(recyclerView, dx, dy);

RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();

//判断是当前layoutManager是否为LinearLayoutManager

// 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法

int lastItemPosition = 0;//最后可见 右边

int firstItemPosition;//第一次可见 右边

if (layoutManager instanceof LinearLayoutManager) {

LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;

//获取最后一个可见view的位置 这两个随便选一个

lastItemPosition = linearManager.findLastVisibleItemPosition();

//获取第一个可见view的位置

firstItemPosition = linearManager.findFirstVisibleItemPosition();

Log.e("可见item的位置--->>","最后一个可见=="+lastItemPosition+ "第一个可见==" + firstItemPosition);

}

//设置左边的RecyclerView的被点击

classifyRVAdapterLeft.setSelectedPosition(lastItemPosition);

//刷新左边的RecyclerV

你可能感兴趣的:(android二级联动简书)