android开发学习 ------- RecyclerView多类型实例

Posted 蒙小米

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android开发学习 ------- RecyclerView多类型实例相关的知识,希望对你有一定的参考价值。

实现RecyclerView多类型的实例:效果如下图所示

public class CarFragment extends Fragment{

    private View view;

    private RecyclerView recycler;

    private CarAdapter madapter ;

    int colors[] = {R.color.app_color,R.color.oklib_frame_black,R.color.white};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_car,container,false);

        //在布局中找到定义
        recycler = view.findViewById(R.id.recyclerview);
        //grid一行有2列的意思
        final GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(),2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                int type = recycler.getAdapter().getItemViewType(position);
                if(type == DataModel.TYPE_THREE){
                    return gridLayoutManager.getSpanCount();
                }else{
                    return 1; //占据一个单元格
                }
            }
        });

        //设置布局管理器
//        recycler.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,
//                false));
        recycler.setLayoutManager(gridLayoutManager);

        madapter =  new CarAdapter(getContext());
        //设置适配器
        recycler.setAdapter(madapter);
        //添加item之间的分割线
        recycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                //super.getItemOffsets(outRect, view, parent, state);
                GridLayoutManager.LayoutParams layoutParams = (GridLayoutManager.LayoutParams) view.getLayoutParams();

                int spansize = layoutParams.getSpanSize();
                int spanindex = layoutParams.getSpanIndex();
                outRect.top = 20;
                if(spansize != gridLayoutManager.getSpanCount()){
                    if(spanindex == 1){
                        outRect.left = 10;
                    }else{
                        outRect.right = 10;
                    }
                }
            }
        });

        initData();
        return view;
    }

    /**
     * 模拟list集合.
     * 针对三种不同的类型,可以去写三个实体类来代替DataModel.
     *
     */
    private void initData(){

        List<DataModel> list = new ArrayList<>();
         for(int i = 0;i < 30; i++){
             //int type = (int)(Math.random()*3)+1;
             int type ;
              if( i < 6 || (i>15 && i<20)){
                type = 1;
              }else if(i<10 || i>26){
                  type = 2;
              }else{
                  type = 3;
              }

             DataModel data = new DataModel();
             data.avatarColor = colors[type - 1];
             data.type = type;
             data.content = "content:"+i;
             data.name = "name:"+i;
             data.contentColor = colors[(type+1)%3];
             list.add(data);
         }
        madapter.addList(list);
        madapter.notifyDataSetChanged(); 
    }
}
public class DataModel {

    public int type;
    public int avatarColor;
    public String name;
    public String content;
    public int contentColor;
    /**
     * 静态常量去区分类型 , 需要创建三个不同的布局
     */
    public static final int TYPE_ONR = 1;
    public static final int TYPE_TWO = 2;
    public static final int TYPE_THREE = 3;

}
public class CarAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private LayoutInflater mLayoutInfater;
    private List<DataModel> mList = new ArrayList<>();

    public CarAdapter(Context context) {
        mLayoutInfater = LayoutInflater.from(context);
    }

    public void addList(List<DataModel> list) {
        mList.addAll(list);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case DataModel.TYPE_ONR:
                return new TypeOneViewHolder(mLayoutInfater.inflate(R.layout.item_car1,parent,false));
            case DataModel.TYPE_TWO:
                return new TypeTwoViewHolder(mLayoutInfater.inflate(R.layout.item_car2,parent,false));
            case DataModel.TYPE_THREE:
                return new TypeThreeViewHolder(mLayoutInfater.inflate(R.layout.item_car3,parent,false));
        }

        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        //判断需要获取哪个数据
        int viewType = getItemViewType(position);
        ((TypeAbstractViewHolder)holder).bindHolder(mList.get(position));
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return mList.get(position).type;
    }
}
public class TypeOneViewHolder extends TypeAbstractViewHolder{

    public ImageView avator;
    public TextView name;

    public TypeOneViewHolder(View itemView) {
        super(itemView);
        avator = itemView.findViewById(R.id.avator);
        name = itemView.findViewById(R.id.name);
    }

    @Override
    public void bingHolder(DataModel model) {
        avator.setBackgroundResource(model.avatarColor);
        name.setText(model.name);
    }
}
public class TypeTwoViewHolder extends TypeAbstractViewHolder{

    public ImageView avator;
    public TextView name;
    public TextView content ;

    public TypeTwoViewHolder(View itemView) {
        super(itemView);
        avator = itemView.findViewById(R.id.avator);
        name = itemView.findViewById(R.id.name);
        content = itemView.findViewById(R.id.content);
    }

    @Override
    public void bingHolder(DataModel model) {
        avator.setBackgroundResource(model.avatarColor);
        name.setText(model.name);
        content.setText(model.content);
    }
}
public class TypeThreeViewHolder extends TypeAbstractViewHolder{

    public ImageView avator;
    public TextView name;
    public TextView content ;
    public ImageView contentImage;

    public TypeThreeViewHolder(View itemView) {
        super(itemView);
        avator = itemView.findViewById(R.id.avator);
        name = itemView.findViewById(R.id.name);
        content = itemView.findViewById(R.id.content);
        contentImage = itemView.findViewById(R.id.contentImage);
    }

    @Override
    public void bingHolder(DataModel model) {
        avator.setBackgroundResource(model.avatarColor);
        name.setText(model.name);
        content.setText(model.content);
        contentImage.setBackgroundResource(model.contentColor);
    }
}

fragment_car.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/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</LinearLayout>

item_car1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="60dp"
    android:layout_width="match_parent"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/avator"
        android:layout_marginLeft="20dp"/>
    <TextView
        android:id="@+id/name"
        android:text="lemon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

item_car2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="60dp"
    android:layout_width="match_parent"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/avator"
        android:layout_marginLeft="20dp"/>
    <LinearLayout
        android:layout_marginLeft="20dp"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/name"
            android:text="lemon"
            android:textSize="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/content"
            android:text="lemon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

item_car3.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="60dp"
    android:layout_width="match_parent"
    android:gravity="center_vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <ImageView
        android:layout_centerVertical="true"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/avator"
        android:layout_marginLeft="20dp"/>

    <LinearLayout
        android:id="@+id/ll"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/avator"
        android:layout_marginLeft="20dp"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/name"
            android:text="lemon"
            android:textSize="20dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/content"
            android:text="lemon"
            android:layout_marginTop="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <ImageView
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@id/ll"
        android:layout_marginRight="20dp"
        android:layout_centerVertical="true"
        android:id="@+id/contentImage"
        android:layout_width="46dp"
        android:layout_height="46dp" />
</RelativeLayout>

 

public abstract class TypeAbstractViewHolder extends RecyclerView.ViewHolder {
    public TypeAbstractViewHolder(View itemView) {
        super(itemView);
    }
    public abstract void bindHolder(DataModel model);
}

 

以上是关于android开发学习 ------- RecyclerView多类型实例的主要内容,如果未能解决你的问题,请参考以下文章

android进阶篇02RecyclerView回收复用机制源码解析

性能优化4--Bitmap内存优化

ArrayList<String> 使用改造 android 解析成 recyclerview

android RecyclerView pinch zoom,ScaleGestureDetector&GridLayoutManager,with BigImageViewer,java

转Android开发学习总结——搭建最新版本的Android开发环境

android开发难学吗? Android开发学习方法