android中用RecyclerView实现滑动删除与切换item

[TOC]

效果图

img

代码

需要注意的地方用注释给出。

可以在github上下载源码。点我试试

RecyclerView1Activity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package com.qefee.pj.testrecyclerview;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class RecyclerView1Activity extends AppCompatActivity {

/**
* 数据集合.
*/

private List<String> dataList;
/**
* RecyclerView的适配器.
*/

private MyAdapter adapter;

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

initDataList();
initRecyclerView();
}

private void initFloatingActionButton() {
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}

private void initActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();

if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}

private void initRecyclerView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this)); // 布局管理器
adapter = new MyAdapter(this, dataList);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); // 分割线
recyclerView.setItemAnimator(new DefaultItemAnimator()); // 动画效果
MyItemTouchHelperCallback callback = new MyItemTouchHelperCallback(adapter); // 监听touch事件,拖拽和滑动等
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView); // 绑定到RecyclerView
}

private void initDataList() {
dataList = new ArrayList<>();

for (int i = 0; i < 20; i++) {
dataList.add(String.format("item %d", i));
}
}

class MyItemTouchHelperCallback extends ItemTouchHelper.Callback {

MyAdapter adapter;

MyItemTouchHelperCallback(MyAdapter adapter) {
this.adapter = adapter;
}

@Override
public boolean isLongPressDragEnabled() {
return true;
}

@Override
public boolean isItemViewSwipeEnabled() {
return true;
}

@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN; // 拖拽方向
int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; // 滑动方向
return makeMovementFlags(dragFlags, swipeFlags);
}

@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
int from = viewHolder.getAdapterPosition();
int to = target.getAdapterPosition();
Collections.swap(adapter.dataList, from, to); // 移动item后要交换数据
adapter.notifyItemMoved(from, to); // 通知适配器数据已经移动
return true;
}

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
switch (direction) {
case ItemTouchHelper.START:
case ItemTouchHelper.END:
int adapterPosition = viewHolder.getAdapterPosition();
adapter.dataList.remove(adapterPosition); // 滑动item后删除数据
adapter.notifyItemRemoved(adapterPosition); // 通知适配器数据已经删除
break;
default:
break;
}
}
}


class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

Context context;
List<String> dataList;

MyAdapter(Context context, List<String> dataList) {
this.context = context;
this.dataList = dataList;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
MyViewHolder vh = new MyViewHolder(view);

return vh;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.text1.setText(dataList.get(position));
}

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

class MyViewHolder extends RecyclerView.ViewHolder {

TextView text1;

MyViewHolder(View itemView) {
super(itemView);

text1 = (TextView) itemView;

text1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(RecyclerView1Activity.this, String.format("text1 on click. index = %d", getAdapterPosition()), Toast.LENGTH_SHORT).show();
}
});

text1.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
Toast.makeText(RecyclerView1Activity.this, String.format("text1 on long click. index = %d", getAdapterPosition()), Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_recycler_view_1, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
switch (id) {
case R.id.itemAdd:


if (dataList.size() > 0) {
Random random = new Random();
int nextInt = random.nextInt(dataList.size());
dataList.add(nextInt, String.format("这里是添加项 %d", nextInt));

adapter.notifyItemInserted(nextInt);
return true;
} else {
int i = 0;
dataList.add(i, String.format("这里是添加项 %d", i));

adapter.notifyItemInserted(i);
}

return true;
case R.id.itemDelete:

if (dataList.size() > 0) {
Random random1 = new Random();
int nextInt1 = random1.nextInt(dataList.size());
dataList.remove(nextInt1);

adapter.notifyItemRemoved(nextInt1);
return true;
} else {
Toast.makeText(this, "没有可删的了", Toast.LENGTH_SHORT).show();
}
default:
break;
}

return super.onOptionsItemSelected(item);
}

}

activity_recycler_view1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.qefee.pj.testrecyclerview.RecyclerView1Activity">


<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">


<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />


</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_recycler_view1" />

<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />


</android.support.design.widget.CoordinatorLayout>

content_recycler_view1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_recycler_view1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.qefee.pj.testrecyclerview.RecyclerView1Activity"
tools:showIn="@layout/activity_recycler_view1">


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


</RelativeLayout>

参考文章

原文

Fork me on GitHub