RecyclerView实现全选,置顶,拖拽功能

DominikHaig 5年前
   <p>今天给大家分享是如何在RecyclerView实现全选,ItemTouchHelper实现侧滑删除,拖拽功能。比较基础。关于RecyclerView的强大,就不多说了。</p>    <p>效果:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/cdc375028ca1caf3d89571627ef8371c.gif"></p>    <p>RecyclerView实现全选,ItemTouchHelper实现侧滑删除,拖拽功能</p>    <p>使用RecyclerView,首先我们需要依赖</p>    <pre>  <code class="language-java">compile 'com.android.support:recyclerview-v7:23.+'</code></pre>    <p>项目结构:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/3075474957d24f273f5ba6cce6669fdf.jpg"></p>    <p>项目结构</p>    <p>主要是把选择的存储在HashMap记录下来,通知用eventbus发送。</p>    <p>下面我们一步一步来实现这种效果.</p>    <p>1、我们新建一个MainActivity 布局</p>    <pre>  <code class="language-java">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 + "项");                      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 + "项");      }      @Override      protected void onDestroy() {          super.onDestroy();          event.unregister(this);      }  }</code></pre>    <p>2、我们建一个ListAdapter适配器</p>    <pre>  <code class="language-java">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));//防止划回来时选中消失            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();      }        /**       * 点击事件和长按事件       */      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;      }  }</code></pre>    <p>3、我们新建实体Book和SelectEvent</p>    <pre>  <code class="language-java">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;      }  }</code></pre>    <p>4、建立checkbox_selector.xml选中样式</p>    <pre>  <code class="language-java"><?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></code></pre>    <p>5、建立一个activity_main.xml布局</p>    <pre>  <code class="language-java"><?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项" />      </LinearLayout>        <android.support.v7.widget.RecyclerView          android:id="@+id/recyclerview"          android:layout_width="match_parent"          android:layout_height="match_parent" />  </LinearLayout></code></pre>    <p>activity_main_item布局</p>    <pre>  <code class="language-java"><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></code></pre>    <p>这样关于RecyclerView实现全选,ItemTouchHelper实现侧滑删除,拖拽功能就完成了。</p>    <p>RecyclerView实现全选,ItemTouchHelper实现侧滑删除,拖拽功能</p>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/7082b7d10760</p>    <p> </p>