Bootstrap

自定义View--RecyclerView

自定义View–RecyclerView

使用RecyvlerView替代ListView依然是趋势,它可以更好的显示大量的数据,所以我们来自定义一个RecyclerView,让它具有更多的使用功能。

自定义view的目的:

  1. 增加左滑显示删除按钮
  2. 点击删除按钮删除这一条数据

在这里插入图片描述

首先自定义RecyclerView需要新建三个文件,FxRecycleListView.javaFxRecycleListViewAdapter.javaFxRecycleModel.java

FxRecycleListView.java

自定义RecyclerView,继承RecyclerView

package com.felix.baselibrary.UI.recyclerview;

import android.content.Context;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class FxRecycleListView extends RecyclerView {
   
    public FxRecycleListView(@NonNull Context context) {
   
        this(context, null);
    }

    public FxRecycleListView(@NonNull Context context, @Nullable AttributeSet attrs) {
   
        this(context, attrs, 0);
    }

    public FxRecycleListView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
   
        super(context, attrs, defStyle);
        initView(context, attrs);

    }

    private void initView(Context context, AttributeSet attrs) {
   
        addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        setLayoutManager(new LinearLayoutManager(context));
    }
}

没做什么特殊的处理,只是加入必要的两行代码,防止编写时遗漏。这两行代码是写RecyclerView必须加的两行代码

addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
setLayoutManager(new LinearLayoutManager(context));

FxRecycleModel.java

实体类,主要为了给adapter数据

package com.felix.baselibrary.UI.recyclerview;

import android.content.Context;
import android.graphics.drawable.Drawable;

public class FxRecycleModel {
   
    private static FxRecycleModel recycleModel;
    private String title;
    private String content;
    private Drawable image;
    private boolean isOpen = false;

    public String getTitle() {
   
        return title;
    }

    public String getContent() {
   
        return content;
    }

    public Drawable getImageView() {
   
        return image;
    }

    public boolean isOpen() {
   
        return isOpen;
    }

    private FxRecycleModel() {
   
    }


    public static class Builder {
   
        private String title = "";
        private String content = "";
        private Drawable image = null;
        private boolean isOpen = 
;