RecyclerView<第六篇>:支持多类型recycleview

这节文章的代码是基于线性recyclerview常规用法改进的。

改动量有点大。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private MultiMainAdapter adapter;

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

        mRecyclerView = findViewById(R.id.recycler_view);
//            mRecyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
//            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setHasFixedSize(true);
        final List<BaseBean> list = new ArrayList<>();
        list.add(new PhotoBean("http://www.17qq.com/img_qqtouxiang/75200019.jpeg", "图片1", (byte) -1));
        list.add(new PhotoBean("http://www.xinhuanet.com//foto/2017-04/26/129575007_14931880312131n.jpg", "图片2", (byte) -1));
        list.add(new PhotoBean("http://img14.360buyimg.com/n1/jfs/t20803/318/567017352/327934/3f2fc045/5b11e4c4N9b82a9ae.jpg", "图片3", (byte) -1));
        list.add(new PhotoBean("http://news.cri.cn/gb/mmsource/images/2007/09/21/em070921050.jpg", "图片4", (byte) -1));
        list.add(new PictureBean("http://pic.58pic.com/58pic/11/68/32/08658PICred.jpg"));
        list.add(new PhotoBean("http://pic19.nipic.com/20120210/7827303_221233267358_2.jpg", "图片5", (byte) -1));
        list.add(new PhotoBean("http://pic.58pic.com/58pic/15/23/09/74T58PICZjg_1024.jpg", "图片6", (byte) -1));
        list.add(new TextBean("我是一个文本1"));
        list.add(new PhotoBean("http://pic.wenwen.soso.com/p/20110311/20110311153941-1798960341.jpg", "图片7", (byte) -1));
        list.add(new TextBean("我是一个文本2"));
        list.add(new PhotoBean("http://news.cri.cn/gb/mmsource/images/2011/05/25/249fe9d0a44e4d1daf28ba20f96930f2.jpg", "图片8", (byte) -1));
        list.add(new PhotoBean("http://www.hb.chinanews.com/photo/2013/1105/U4P1T52D145F1033DT20131105102009.jpg", "图片9", (byte) -1));
        list.add(new PictureBean("http://pic.nipic.com/2008-05-06/200856201542395_2.jpg"));
        list.add(new PhotoBean("http://gz.people.com.cn/mediafile/201110/12/F201110121633301826600704.jpg", "图片10", (byte) -1));
        list.add(new PhotoBean("http://imgpic.gmw.cn/dt/2012-02/15/20120215143754_7556.jpg", "图片11", (byte) -1));
        list.add(new TextBean("我是一个文本3"));



        adapter = new MultiMainAdapter(MainActivity.this, list, new MultiRecycleViewListener<BaseBean>() {
            @Override
            public int getItemViewType(int position) {
                int itemViewType = 0;
                if(list != null && list.size() > 0){
                    itemViewType = list.get(position).getItemViewType();
                }
                return itemViewType;
            }

            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = null;
                RecyclerView.ViewHolder holder = null;
                switch (viewType){
                    case ItemType.TYPE_0:
                        itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.recycleview_item, parent, false);
                        holder = new PhotoViewHolder(itemView);
                        break;
                    case ItemType.TYPE_1:
                        itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.text_layout, parent, false);
                        holder = new TextViewHolder(itemView);
                        break;
                    case ItemType.TYPE_2:
                        itemView = LayoutInflater.from(MainActivity.this).inflate(R.layout.pic_layout, parent, false);
                        holder = new PictureViewHolder(itemView);
                        break;
                    case ItemType.TYPE_3:
                        break;
                    case ItemType.TYPE_4:
                        break;
                    case ItemType.TYPE_5:
                        break;

                }
                return holder;
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder myholder, int position, @NonNull List<Object> payloads) {

                if(myholder instanceof PhotoViewHolder){
                    PhotoViewHolder holder = (PhotoViewHolder) myholder;
                    if(payloads.get(0) instanceof PhotoBean){
                        PhotoBean photoBean = (PhotoBean) payloads.get(0);

                        if(photoBean.getClickButton() == 2){
                            holder.button_2.setBackgroundColor(Color.YELLOW);
                        }
                    }
                }

            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onBindViewHolder(final RecyclerView.ViewHolder myholder, final int position) {

                if(myholder instanceof PhotoViewHolder){
                    PhotoViewHolder holder = (PhotoViewHolder) myholder;
                    final PhotoBean photoBean = (PhotoBean) list.get(position);

                    Glide.with(MainActivity.this).load(photoBean.getUrl()).into(holder.imgView);
                    holder.tvName.setText(photoBean.getName());
                    if(photoBean.getClickButton() == 2){
                        holder.button_2.setBackgroundColor(Color.YELLOW);
                    }else{
                        holder.button_2.setBackground(null);
                    }

                    holder.imgView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "点击了图片", Toast.LENGTH_SHORT).show();
                        }
                    });

                    holder.button_1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "点击了按钮1", Toast.LENGTH_SHORT).show();
                            photoBean.setName("修改!");
                            photoBean.setUrl("http://pic29.nipic.com/20130511/9252150_174018365301_2.jpg");
                            adapter.notifyItemChanged(position);
                        }
                    });

                    holder.button_2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "点击了按钮2", Toast.LENGTH_SHORT).show();
                            photoBean.setClickButton((byte) 2);
                            adapter.notifyItemChanged(position, photoBean);
                        }
                    });

                    holder.button_3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "添加Item", Toast.LENGTH_SHORT).show();
                            list.add(position, new PhotoBean(photoBean.getUrl(), photoBean.getName(), photoBean.getClickButton()));
                            adapter.notifyItemInserted(position);
                            if(position != list.size()){
                                adapter.notifyItemRangeChanged(position, list.size() - position);
                            }
                        }
                    });

                    holder.button_4.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "删除Item", Toast.LENGTH_SHORT).show();
                            list.remove(position);
                            adapter.notifyItemRemoved(position);
                            if(position != list.size()){
                                adapter.notifyItemRangeChanged(position, list.size() - position);
                            }
                        }
                    });


                    holder.button_5.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(MainActivity.this, "移动Item", Toast.LENGTH_SHORT).show();
                            Collections.swap(list,position,position+1);// 元素互换
                            adapter.notifyItemMoved(position, position + 1);
                            if(position != list.size()){
                                adapter.notifyItemRangeChanged(position, list.size() - position);
                            }
                        }
                    });
                }else if(myholder instanceof TextViewHolder){
                    TextViewHolder holder = (TextViewHolder) myholder;
                    TextBean textBean = (TextBean) list.get(position);
                    holder.tv_text.setText(textBean.getText() == null ? "" : textBean.getText());
                }else if(myholder instanceof PictureViewHolder){
                    PictureViewHolder holder = (PictureViewHolder) myholder;
                    PictureBean pictureBean = (PictureBean) list.get(position);
                    Glide.with(MainActivity.this).load(pictureBean.getUrl()).into(holder.picture);

                }
            }
        });
        mRecyclerView.setAdapter(adapter);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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"
    tools:context=".MainActivity">

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


</android.support.constraint.ConstraintLayout>

MultiMainAdapter.java(为了使Adapter通用性,我把说有的数据处理和界面处理都移到Activity类里面了)

import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;

import java.util.List;

public class MultiMainAdapter<T> extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private Context mContext;
    private List<T> mData;
    private MultiRecycleViewListener listener;

    public MultiMainAdapter(Context context, List<T> mData, MultiRecycleViewListener listener) {
        this.mContext = context;
        this.mData = mData;
        this.listener = listener;
    }

    /**
     * 设置数据
     * @param mData
     */
    public void setData(List<T> mData){
        this.mData = mData;
    }

    @Override
    public int getItemViewType(int position) {
        return listener.getItemViewType(position);
    }


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


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return listener.onCreateViewHolder(parent, viewType);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads) {
        if(payloads != null && !payloads.isEmpty()){
            listener.onBindViewHolder(holder, position, payloads);
        }else{
            onBindViewHolder(holder, position);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        listener.onBindViewHolder(holder, position);
    }
}

MultiRecycleViewListener.java

public interface MultiRecycleViewListener<T> {

    int getItemViewType(int position);

    RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType);

    void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position, @NonNull List<Object> payloads);

    void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position);

}

ItemType.java

public class ItemType {

    //PhotoBean类型
    public static final int TYPE_0 = 0;
    //纯文本类型
    public static final int TYPE_1 = 1;
    //纯图片类型
    public static final int TYPE_2 = 2;
    //按钮类型
    public static final int TYPE_3 = 3;
    //单选类型
    public static final int TYPE_4 = 4;
    //多选类型
    public static final int TYPE_5 = 5;

}

PhotoViewHolder.java

public class PhotoViewHolder extends RecyclerView.ViewHolder {
    public ImageView imgView;
    public TextView tvName;
    public Button button_1, button_2,button_3, button_4, button_5;

    public TextView tv_text;


    public PhotoViewHolder(@NonNull View itemView) {
        super(itemView);
        imgView = itemView.findViewById(R.id.image);
        tvName = itemView.findViewById(R.id.text);
        button_1 = itemView.findViewById(R.id.button_1);
        button_2 = itemView.findViewById(R.id.button_2);
        button_3 = itemView.findViewById(R.id.button_3);
        button_4 = itemView.findViewById(R.id.button_4);
        button_5 = itemView.findViewById(R.id.button_5);
    }
}

TextViewHolder.java

public class TextViewHolder extends RecyclerView.ViewHolder {

    public TextView tv_text;

    public TextViewHolder(View itemView) {
        super(itemView);
        tv_text = itemView.findViewById(R.id.tv_text);

    }

}

PictureViewHolder.java

public class PictureViewHolder extends RecyclerView.ViewHolder {
    public ImageView picture;

    public PictureViewHolder(View itemView) {
        super(itemView);
        picture = itemView.findViewById(R.id.picture);

    }
}

BaseBean.java

public class BaseBean {

    //Item类型
    private int itemViewType;

    public int getItemViewType() {
        return itemViewType;
    }

    public void setItemViewType(int itemViewType) {
        this.itemViewType = itemViewType;
    }
}

PhotoBean.java

public class PhotoBean extends BaseBean{

    private String name;

    private String url;

    private byte clickButton;//0:点击了图片,1:点击了按钮1,2:点击了按钮2

    public PhotoBean(){}

    public PhotoBean(String url, String name, byte clickButton){
        this.url = url;
        this.name = name;
        this.clickButton = clickButton;
        this.setItemViewType(ItemType.TYPE_0);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public byte getClickButton() {
        return clickButton;
    }

    public void setClickButton(byte clickButton) {
        this.clickButton = clickButton;
    }
}

TextBean.java

public class TextBean extends BaseBean {

    private String text;

    public TextBean(String text){
        this.text = text;
        this.setItemViewType(ItemType.TYPE_1);
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

PictureBean.java

public class PictureBean extends BaseBean {

    private String url;

    public PictureBean(String url){
        this.url = url;
        this.setItemViewType(ItemType.TYPE_2);
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

recycleview_item.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/bgbgbg"
    android:orientation="vertical"
    android:layout_margin="5dp">


    <com.jiangxi.login.myapplication.CustomImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:scaleType="centerCrop"
        android:paddingBottom="5dp"
        android:layout_gravity="center_horizontal" />


    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_gravity="center_horizontal"
        android:textSize="18sp"
        android:text="11111111111111111111111111111111111111111111111111111111"
        android:gravity="center_horizontal"
        android:lines="1"
        android:ellipsize="end"
        android:textColor="@color/colorAccent"
        android:visibility="visible" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center_horizontal"
        android:padding="10dp">

        <Button
            android:id="@+id/button_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮1"/>

        <Button
            android:id="@+id/button_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:text="按钮2"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_gravity="center_horizontal">

        <Button
            android:id="@+id/button_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="添加"/>

        <Button
            android:id="@+id/button_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="删除"/>

        <Button
            android:id="@+id/button_5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="移动"/>
    </LinearLayout>
</LinearLayout>

text_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/bgbgbg">

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:textSize="20sp"
        android:textColor="@color/colorAccent"/>
</android.support.constraint.ConstraintLayout>

pic_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/bgbgbg">

    <com.jiangxi.login.myapplication.CustomImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:scaleType="centerCrop"
        android:paddingBottom="5dp"
        android:layout_gravity="center_horizontal" />

</android.support.constraint.ConstraintLayout>

CustomImageView.java

import android.content.Context;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

public class CustomImageView extends AppCompatImageView {

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

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int width = MeasureSpec.getSize(widthMeasureSpec);

        setMeasuredDimension(width, width);
    }

}

以上就是多类型recycleview的所有代码了。

16.gif

最后本人要强调一下重要知识点:写Demo太辛苦了,点个赞再走呗

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,922评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,591评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,546评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,467评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,553评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,580评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,588评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,334评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,780评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,092评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,270评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,925评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,573评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,194评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,437评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,154评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,127评论 2 352

推荐阅读更多精彩内容