Android RecyclerView多型別佈局卡片解決方案

luokanghui發表於2019-03-18

背景

隨著公司業務越來越複雜,在同一個列表中需要展示各種型別的資料。

總體結構

類圖

  • ItemViewAdapter: 每種型別的卡片分別都是不同的ItemViewAdapter
  • ItemViewAdapterFactory: 使用ItemViewAdapterFactory根據不同資料對應不同的ItemViewAdapter
  • MultiRecyclerViewAdapter: MultiRecyclerViewAdapter就是RecylerView.Adapter,並是個ItemViewAdapterFactory。 具體只要繼承MultiRecyclerViewAdapter即可,實現ItemViewAdapterFactory中getViewType、onCreateItemViewAdapter兩個方法
  • ContextMap: 整個Adapter共用一個ContextMap資料上下文,用於外部(例Fragment等)與ItemAdapter互動、ItemAdapter之間互動等一系列資料傳遞,可以解決引數層層傳遞的問題
  • RecyclerViewHolder: 通用RecyclerView.ViewHolder,封裝根據id獲取view方法getView(viewId)、獲取資料上下文方法getContextMap()

使用方法

  • 每種型別卡片Item都實現ItemViewAdapter
package com.lkh.multiadapter;

import android.support.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;

/**
 * 列表單項佈局與資料繫結
 * Created by luokanghui on 2017/5/24.
 */
public abstract class ItemViewAdapter<E>{

    /**
     * 返回列表單項View,如果View由資源layout載入而來,直接重寫{@link #onGetLayoutId()}即可
     * @param parent 父view,一般為RecyclerView
     * @return 列表單項View
     */
    public View onCreateView(ViewGroup parent){
        return LayoutInflater.from(parent.getContext()).inflate(onGetLayoutId()
                , parent, false);
    }

    /**
     * 當RecyclerViewHolder建立成功後呼叫,只會呼叫一次
     * @param viewHolder 單項view集合
     */
    public void onCreate(RecyclerViewHolder viewHolder){

    }

    /**
     * 返回單項佈局的資源id,如果重寫了{@link #onCreateView(ViewGroup)},則此方法可能失效
     * @return 單項佈局layout id
     */
    @LayoutRes
    protected abstract int onGetLayoutId();

    /**
     * 把資料與view進行繫結,滑動時都會呼叫
     * @param viewHolder 單項view集合
     * @param data 具體資料
     * @param position 在列表中的位置
     */
    public abstract void bindData(RecyclerViewHolder viewHolder, E data, int position);

    /**
     * 區域性更新時呼叫
     * @param viewHolder 單項view集合
     * @param data 具體資料
     * @param position 在列表中的位置
     * @param payloads 區域性更新標誌,不會為空(isEmpty()==false)
     */
    public void bindData(RecyclerViewHolder viewHolder, E data, int position, List<Object> payloads){

    }
}
複製程式碼

卡片1:

package com.lkh.multiadapter.sample;

import android.widget.TextView;

import com.lkh.multiadapter.ItemViewAdapter;
import com.lkh.multiadapter.R;
import com.lkh.multiadapter.RecyclerViewHolder;

/**
 * 卡片1實現
 * Created by luokanghui on 2019/3/18
 */
public class SampleOneItemViewAdapter extends ItemViewAdapter<DataOne> {
    @Override
    protected int onGetLayoutId() {
        //佈局layout資源id
        return R.layout.item_one;
    }

    @Override
    public void bindData(RecyclerViewHolder viewHolder, DataOne data, int position) {
        //根據id獲取view
        TextView tvContent = viewHolder.getView(R.id.tv_content);
        //資料繫結
        tvContent.setText(data.getContent());
    }
}
複製程式碼
package com.lkh.multiadapter.sample;

/**
 * 卡片1資料
 * Created by luokanghui on 2019/3/18
 */
public class DataOne {
    private String content;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
複製程式碼

item_one.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#eeeeee"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="卡片1"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:gravity="center"
        android:textColor="#000000" />

</LinearLayout>
複製程式碼

卡片2

package com.lkh.multiadapter.sample;

import android.widget.TextView;

import com.lkh.multiadapter.ItemViewAdapter;
import com.lkh.multiadapter.R;
import com.lkh.multiadapter.RecyclerViewHolder;

/**
 * 卡片2實現
 * Created by luokanghui on 2019/3/18
 */
public class SampleTwoItemViewAdapter extends ItemViewAdapter<DataTwo> {
    @Override
    protected int onGetLayoutId() {
        //佈局layout資源id
        return R.layout.item_two;
    }

    @Override
    public void bindData(RecyclerViewHolder viewHolder, DataTwo data, int position) {
        //根據id獲取view
        TextView tvNum = viewHolder.getView(R.id.tv_num);
        //資料繫結
        tvNum.setText("num="+data.getNum());
    }
}
複製程式碼
package com.lkh.multiadapter.sample;

/**
 * 卡片2資料
 * Created by luokanghui on 2019/3/18
 */
public class DataTwo {
    private int num;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }
}
複製程式碼

item_two.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#999999"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="卡片2"
        android:textColor="#0000ff" />

    <TextView
        android:id="@+id/tv_num"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:gravity="center"
        android:textColor="#0000ff" />

</LinearLayout>
複製程式碼
  • 總Adapter,繼承MultiRecyclerViewAdapter
package com.lkh.multiadapter.sample;

import com.lkh.multiadapter.ItemViewAdapter;
import com.lkh.multiadapter.MultiRecyclerViewAdapter;

/**
 * 多佈局adapter,根據不同data及position,使用不同ItemViewAdapter卡片
 * Created by luokanghui on 2019/3/18
 */
public class SampleMultiAdapter extends MultiRecyclerViewAdapter<Object> {
    private static final int TYPE_EMPTY = 0;//空item
    private static final int TYPE_ONE = 1;//卡片1
    private static final int TYPE_TWO = 2;//卡片2

    @Override
    public int getViewType(Object data, int position) {
        if (data instanceof DataOne){//卡片1
            return TYPE_ONE;
        }

        if (data instanceof DataTwo){//卡片2
            return TYPE_TWO;
        }

        return TYPE_EMPTY;//空item
    }

    @Override
    public ItemViewAdapter onCreateItemViewAdapter(int viewType) {
        switch (viewType){
            case TYPE_ONE://卡片1
                return new SampleOneItemViewAdapter();
            case TYPE_TWO://卡片2
                return new SampleTwoItemViewAdapter();
            default://空item
                return new EmptyItemViewAdapter();
        }
    }
}
複製程式碼
  • RecyclerView中使用
package com.lkh.multiadapter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.lkh.multiadapter.sample.DataOne;
import com.lkh.multiadapter.sample.DataTwo;
import com.lkh.multiadapter.sample.SampleMultiAdapter;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        SampleMultiAdapter adapter = new SampleMultiAdapter();

        //設定資料
        adapter.setData(generateData());

        //設定adapter
        recyclerView.setAdapter(adapter);

    }

    //造測試資料
    private List<Object> generateData(){
        List<Object> list = new ArrayList<>();
        for (int i=0; i<20; i++){
            DataOne dataOne = new DataOne();
            dataOne.setContent("這是卡片1資料:"+i);
            list.add(dataOne);

            DataTwo dataTwo = new DataTwo();
            dataTwo.setNum(i);
            list.add(dataTwo);
        }
        return list;
    }
}
複製程式碼

activity_main.xml:

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

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

</LinearLayout>
複製程式碼
  • 執行效果如下:

    Android RecyclerView多型別佈局卡片解決方案
    )

  • 總的來說,實現一個多型別佈局列表只需要寫多個不同卡片ItemViewAdapter、繼承MultiRecyclerViewAdapter用來控制不同資料使用不同ItemViewAdapter,新增一個卡片只需要新增一個ItemViewAdapter,在MultiRecyclerViewAdapter新加一項即可,不會影響其它卡片使用,而且ItemViewAdapter完全獨立,可以很好的複用。

核心程式碼

package com.lkh.multiadapter;

import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import java.util.List;

/**
 * 多種佈局adapter
 * Created by luokanghui on 2017/5/24.
 */

public abstract class MultiRecyclerViewAdapter<E> extends RecyclerView.Adapter<RecyclerViewHolder> implements ItemViewAdapterFactory<E> {
    public static final int NO_TYPE = -1;

    private List<E> dataList;

    protected final MapData mMapData = new MapData();

    public MultiRecyclerViewAdapter setData(List<E> list) {
        this.dataList = list;
        return this;
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ItemViewAdapter itemViewModule = onCreateItemViewAdapter(viewType);
        RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(itemViewModule.onCreateView(parent), itemViewModule, this, getContextMap());
        itemViewModule.onCreate(recyclerViewHolder);
        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position) {
        if (checkItems(position)) {
            return;
        }
        holder.itemViewAdapter.bindData(holder, dataList.get(position), position);
    }

    @Override
    public void onBindViewHolder(RecyclerViewHolder holder, int position, List<Object> payloads) {
        if (checkItems(position)) {
            return;
        }
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads);
        } else {
            holder.itemViewAdapter.bindData(holder, dataList.get(position), position, payloads);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (checkItems(position)) {
            return NO_TYPE;
        }
        return getViewType(dataList.get(position), position);
    }

    @Override
    public int getItemCount() {
        return dataList == null ? 0 : dataList.size();
    }

    /**
     * true表示沒通過
     */
    private boolean checkItems(int position) {
        return dataList == null || position < 0 || position >= dataList.size();
    }

    @Override
    public MapData getContextMap() {
        return mMapData;
    }
}
複製程式碼
package com.lkh.multiadapter;


/**
 * 多佈局ItemViewAdapter建立者
 * Created by luokanghui on 2017/5/24.
 */
public interface ItemViewAdapterFactory<E> {

    /**
     * 返回ItemViewAdapter的型別
     * 建議根據data的資料型別判斷不同的viewType
     * @param data 具體資料
     * @param position 在列表中的位置
     * @return 型別
     */
    int getViewType(E data, int position);

    /**
     * 根據不同的viewType返回不同的ItemViewAdapter
     * @param viewType 型別
     * @return ItemViewAdapter
     */
    ItemViewAdapter<? extends E> onCreateItemViewAdapter(int viewType);


    /**
     * 上下文資料
     * @return
     */
    MapData getContextMap();
}
複製程式碼
package com.lkh.multiadapter;

import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;


/**
 * ViewHolder基類
 */
public final class RecyclerViewHolder extends RecyclerView.ViewHolder {

    private final SparseArray<View> views;
    ItemViewAdapter itemViewAdapter;
    private final RecyclerView.Adapter adapter;
    private final MapData mMapData ;


    public RecyclerViewHolder(View itemView, ItemViewAdapter itemViewAdapter, RecyclerView.Adapter adapter, MapData mapData) {
        super(itemView);
        this.views = new SparseArray<>();
        this.itemViewAdapter = itemViewAdapter;
        this.adapter = adapter;
        this.mMapData = mapData;
    }

    /**
     * 根據id獲取view,如果快取中存在,直接使用快取中的,避免重複執行findViewById
     */
    @SuppressWarnings("unchecked")
    public <T extends View> T getView(int viewId) {
        View view = views.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            views.put(viewId, view);
        }
        return (T) view;
    }

    public RecyclerView.Adapter getAdapter(){
        return adapter;
    }

    /**
     * 獲取資料上下文
     */
    public MapData getContextMap(){
        return mMapData;
    }


}
複製程式碼
package com.lkh.multiadapter;

import android.support.annotation.LayoutRes;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * 列表單項佈局與資料繫結
 * Created by luokanghui on 2017/5/24.
 */

public abstract class ItemViewAdapter<E>{

    /**
     * 返回列表單項View,如果View由資源layout載入而來,直接重寫{@link #onGetLayoutId()}即可
     * @param parent 父view,一般為RecyclerView
     * @return 列表單項View
     */
    public View onCreateView(ViewGroup parent){
        return LayoutInflater.from(parent.getContext()).inflate(onGetLayoutId()
                , parent, false);
    }

    /**
     * 當RecyclerViewHolder建立成功後呼叫,只會呼叫一次
     * @param viewHolder 單項view集合
     */
    public void onCreate(RecyclerViewHolder viewHolder){

    }

    /**
     * 返回單項佈局的資源id,如果重寫了{@link #onCreateView(ViewGroup)},則此方法可能失效
     * @return 單項佈局layout id
     */
    @LayoutRes
    protected abstract int onGetLayoutId();

    /**
     * 把資料與view進行繫結,滑動時都會呼叫
     * @param viewHolder 單項view集合
     * @param data 具體資料
     * @param position 在列表中的位置
     */
    public abstract void bindData(RecyclerViewHolder viewHolder, E data, int position);

    /**
     * 區域性更新時呼叫
     * @param viewHolder 單項view集合
     * @param data 具體資料
     * @param position 在列表中的位置
     * @param payloads 區域性更新標誌,不會為空(isEmpty()==false)
     */
    public void bindData(RecyclerViewHolder viewHolder, E data, int position, List<Object> payloads){

    }
}
複製程式碼

相關文章