RecyclerView實(shí)現(xiàn)全選、置頂缤沦、拖拽功能

今天給大家分享是如何在RecyclerView實(shí)現(xiàn)全選虎韵,ItemTouchHelper實(shí)現(xiàn)側(cè)滑刪除,拖拽功能。比較基礎(chǔ)缸废。關(guān)于RecyclerView的強(qiáng)大包蓝,就不多說了驶社。

效果:

RecyclerView實(shí)現(xiàn)全選,ItemTouchHelper實(shí)現(xiàn)側(cè)滑刪除,拖拽功能

使用RecyclerView测萎,首先我們需要依賴

    compile 'com.android.support:recyclerview-v7:23.+'

項(xiàng)目結(jié)構(gòu):

項(xiàng)目結(jié)構(gòu)

主要是把選擇的存儲(chǔ)在HashMap記錄下來亡电,通知用eventbus發(fā)送。

下面我們一步一步來實(shí)現(xiàn)這種效果.

1绳泉、我們新建一個(gè)MainActivity 布局

public class MainActivity extends Activity {
    private RecyclerView recyclerView;
    private CheckBox checkbox;
    private TextView selected;
    private ListAdapter adapter;
    private EventBus event;
    private boolean isChange = false;
    private ArrayList<Book> list = new ArrayList<>();

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

    private void initView() {
        event = EventBus.getDefault();
        event.register(this);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
        selected = (TextView) findViewById(R.id.selected);
    }

    private void initData() {
        for (int i = 0; i < 20; i++) {
            Book model = new Book();
            model.setId(i);
            model.setName("商品" + i);
            model.setDesc("描述" + i);
            list.add(model);
        }
        adapter = new ListAdapter(list, event);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                try {
                    HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
                    int count = 0;
                    if (isChecked) {
                        isChange = false;
                    }
                    for (int i = 0, p = list.size(); i < p; i++) {
                        if (isChecked) {
                            map.put(i, true);
                            count++;
                        } else {
                            if (!isChange) {
                                map.put(i, false);
                                count = 0;
                            } else {
                                map = adapter.getMap();
                                count = map.size();
                            }
                        }
                    }
                    selected.setText("已選" + count + "項(xiàng)");
                    adapter.setMap(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        adapter.setOnItemClickListener(new ListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder holder, int positon) {
                Log.e("onItemClick", "" + positon);
            }

            @Override
            public void onItemLongClick(final RecyclerView.ViewHolder holder, final int positon) {
                Log.e("onItemLongClick", "" + positon);
            }
        });
    }

    public void onEventMainThread(SelectEvent event) {
        int size = event.getSize();
        if (size < list.size()) {
            isChange = true;
            checkbox.setChecked(false);
        } else {
            checkbox.setChecked(true);
            isChange = false;
        }
        selected.setText("已選" + size + "項(xiàng)");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        event.unregister(this);
    }
}

2逊抡、我們建一個(gè)ListAdapter適配器

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ItemViewHolder> {

    private List<Book> mItems;
    private List<Book> selected;
    public HashMap<Integer, Boolean> map;
    private EventBus eventBus;

    public ListAdapter(List<Book> mItems, EventBus eventBus) {
        this.mItems = mItems;
        this.eventBus = eventBus;
        map = new HashMap<>();
        selected = new ArrayList<>();
        init();
    }

    private void init() {
        if (null == mItems || mItems.size() <= 0) {
            return;
        }
        for (int i = 0, p = mItems.size(); i < p; i++) {
            map.put(i, false);
        }
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main_item, parent, false);
        ItemViewHolder itemViewHolder = new ItemViewHolder(view);
        return itemViewHolder;
    }

    @Override
    public void onBindViewHolder(final ItemViewHolder holder, final int position) {
        if (null == mItems || mItems.size() <= 0) {
            return;
        }
        holder.name.setText(mItems.get(position).getName());
        holder.desc.setText(mItems.get(position).getDesc());

        holder.checkBox.setTag(new Integer(position));//防止劃回來時(shí)選中消失

        if (map != null) {
            ((ItemViewHolder) holder).checkBox.setChecked((map.get(position)));
        } else {
            ((ItemViewHolder) holder).checkBox.setChecked(false);
        }
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int mFlags = (Integer) view.getTag();
                if (map != null) {
                    if (map.get(position)) {
                        map.put(position, false);
                        eventBus.post(new SelectEvent(selected(map)));
                    } else {
                        map.put(mFlags, Boolean.TRUE);
                        eventBus.post(new SelectEvent(selected(map)));
                    }
                }
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mItemClickListener.onItemClick(holder,holder.getAdapterPosition());
            }
        });
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mItemClickListener.onItemLongClick(holder,holder.getAdapterPosition());
                return true;
            }
        });
    }

    private int selected(HashMap<Integer, Boolean> map) {
        int size = 0;
        for (Integer key : map.keySet()) {
            if(map.get(key)){
                size++;
            }
        }
        return size;
    }
    @Override
    public int getItemCount() {
        return mItems == null? 0 :mItems.size();
    }
    public static class ItemViewHolder extends RecyclerView.ViewHolder{

        public final CheckBox checkBox;
        public final TextView name;
        public final TextView desc;

        public ItemViewHolder(View itemView) {
            super(itemView);
            checkBox = (CheckBox) itemView.findViewById(R.id.checkbox);
            name = (TextView) itemView.findViewById(R.id.tv_name);
            desc = (TextView) itemView.findViewById(R.id.tv_desc);
        }
    }

    public HashMap<Integer, Boolean> getMap() {
        return map;
    }

    public void setMap(HashMap<Integer, Boolean> map) {
        this.map = map;
        notifyDataSetChanged();
    }

    /**
     * 點(diǎn)擊事件和長按事件
     */
    public interface ItemClickListener{
        void onItemClick(RecyclerView.ViewHolder holder , int position);
        void onItemLongClick(RecyclerView.ViewHolder holder , int position);
    }

    private ItemClickListener mItemClickListener;
    public void setOnItemClickListener(ItemClickListener listener){
        this.mItemClickListener=listener;
    }
}

3、我們新建實(shí)體Book和SelectEvent

package com.aikaifa.checkall.bean;

public class Book {

    private int id;
    private String name;
    private String desc;

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Book() {
    }
}

public class SelectEvent {
    private int size;

    public SelectEvent(int size) {
        this.size = size;
    }

    public int getSize() {
        return size;
    }
}

4零酪、建立checkbox_selector.xml選中樣式

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/checkbox_pressed" android:state_checked="true"/>
    <item android:drawable="@mipmap/checkbox_normal" android:state_checked="false"/>
    <item android:drawable="@mipmap/checkbox_normal"/>
</selector>

5冒嫡、建立一個(gè)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">

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

        <CheckBox
            android:id="@+id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawablePadding="10dp"
            android:text="全選"
            android:textColor="#969696"
            android:textSize="12sp" />

        <TextView
            android:id="@+id/selected"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:gravity="center_vertical"
            android:text="已選0項(xiàng)" />
    </LinearLayout>

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

activity_main_item布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:clickable="true"
    android:focusable="true">

    <RelativeLayout
        android:id="@+id/rl_app"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true">

        <ImageView
            android:id="@+id/iv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher" />

        <CheckBox
            android:id="@+id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_gravity="center_vertical"
            android:button="@drawable/checkbox_selector" />

    </RelativeLayout>

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rl_app"
        android:gravity="center"
        android:text="name"
        android:textColor="#ffffff" />

    <TextView
        android:id="@+id/tv_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_name"
        android:gravity="center"
        android:textColor="#f5f5f5"
        android:textSize="9sp" />
</RelativeLayout>

這樣關(guān)于RecyclerView實(shí)現(xiàn)全選,ItemTouchHelper實(shí)現(xiàn)側(cè)滑刪除,拖拽功能就完成了四苇。

RecyclerView實(shí)現(xiàn)全選孝凌,ItemTouchHelper實(shí)現(xiàn)側(cè)滑刪除,拖拽功能
項(xiàng)目地址
https://github.com/88ios/RecyclerViewCheckAll
【END】

如果你喜歡今天的文章,猜你喜歡:

為什么有的人工作多年還是老樣子

如果你正處于焦慮月腋,不妨看看這篇文章

怕出丑蟀架,只怕會(huì)錯(cuò)過更大的收獲

能力不強(qiáng)時(shí),請不要總是準(zhǔn)時(shí)下班

你必須非常努力榆骚,才能看起來毫不費(fèi)力

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末片拍,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子妓肢,更是在濱河造成了極大的恐慌捌省,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件碉钠,死亡現(xiàn)場離奇詭異纲缓,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)喊废,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門祝高,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人污筷,你說我怎么就攤上這事工闺。” “怎么了瓣蛀?”我有些...
    開封第一講書人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵陆蟆,是天一觀的道長。 經(jīng)常有香客問我揪惦,道長,這世上最難降的妖魔是什么罗侯? 我笑而不...
    開封第一講書人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任器腋,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘纫塌。我一直安慰自己诊县,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開白布措左。 她就那樣靜靜地躺著依痊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪怎披。 梳的紋絲不亂的頭發(fā)上胸嘁,一...
    開封第一講書人閱讀 51,554評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音凉逛,去河邊找鬼性宏。 笑死,一個(gè)胖子當(dāng)著我的面吹牛状飞,可吹牛的內(nèi)容都是我干的毫胜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼诬辈,長吁一口氣:“原來是場噩夢啊……” “哼酵使!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起焙糟,我...
    開封第一講書人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤口渔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后酬荞,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體搓劫,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年混巧,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了枪向。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡咧党,死狀恐怖秘蛔,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情傍衡,我是刑警寧澤深员,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站蛙埂,受9級(jí)特大地震影響倦畅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜绣的,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一叠赐、第九天 我趴在偏房一處隱蔽的房頂上張望欲账。 院中可真熱鬧,春花似錦芭概、人聲如沸赛不。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽踢故。三九已至,卻和暖如春惹苗,著一層夾襖步出監(jiān)牢的瞬間殿较,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來泰國打工鸽粉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留斜脂,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓触机,卻偏偏與公主長得像帚戳,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子儡首,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容