リスト要素順の移動をドラッグ&ドロップとスワイプで削除を行いたいというのがRecyclerViewの目的の一つですが、これにはItemTouchHelperを実装すると可能です。
簡単な設定として ItemTouchHelper.SimpleCallback を試してみます。
2021.2.1
RecycleView & ItemTouchHelper
ItemTouchHelperでは色々できるのですが、簡単にできるGoogle DeveloppersのItemTouchHelper.SimpleCallbackがお勧めです。
基本のItemTouchHelper
を元にして作成してきましょう
データセットは要素を削除したり可変長となるのでArrayListで作ります。
getAdapterPosition()
は非推奨になり代わりに
getBindingAdapterPosition()
getAbsoluteAdapterPosition()
などを使います
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 |
val mIth = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback( // 上下のdragではonMove(), 左右のswipeではonSwiped() ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or or ItemTouchHelper.RIGHT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { // 開始位置と移動先の位置 val fromPos = viewHolder.bindingAdapterPosition val toPos = target.bindingAdapterPosition // adapterに移動したことを通知する adapter.notifyItemMoved(fromPos, toPos) return true // true if moved, false otherwise } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { dataSet.removeAt(viewHolder.bindingAdapterPosition) // adapterに削除されたことを通知する adapter.notifyItemRemoved(viewHolder.bindingAdapterPosition) } }) |
これをRcyclerViewに組み合わせてまとめていきます
MainActivity.kt
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 |
//package your.package.name import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration import java.util.* import kotlin.collections.ArrayList class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view) recyclerView.setHasFixedSize(true) val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this) recyclerView.layoutManager = layoutManager val dataSet: ArrayList<String> = arrayListOf() var i = 0 while (i < 20) { val str: String = java.lang.String.format(Locale.US, "Data_0%d", i) dataSet.add(str) i++ } recyclerView.adapter = MyAdapter(dataSet) val itemDecoration: ItemDecoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL) recyclerView.addItemDecoration(itemDecoration) val adapter = recyclerView.adapter as MyAdapter val mIth = ItemTouchHelper( object : ItemTouchHelper.SimpleCallback( ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val fromPos = viewHolder.bindingAdapterPosition val toPos = target.bindingAdapterPosition adapter.notifyItemMoved(fromPos, toPos) return true // true if moved, false otherwise } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { dataSet.removeAt(viewHolder.bindingAdapterPosition) adapter.notifyItemRemoved(viewHolder.bindingAdapterPosition) } }) mIth.attachToRecyclerView(recyclerView) } } |
アダプターです
MyAdapter.kt
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 |
//package your.package.name import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class MyAdapter(private val dataSet: ArrayList<String>): RecyclerView.Adapter<MyAdapter.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val textView: TextView init { // Define click listener for the ViewHolder's View. textView = view.findViewById(R.id.text_view) } } // Create new views (invoked by the layout manager) override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder { // Create a new view, which defines the UI of the list item val view = LayoutInflater.from(viewGroup.context) .inflate(R.layout.my_text_view, viewGroup, false) return ViewHolder(view) } // Replace the contents of a view (invoked by the layout manager) override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { // Get element from your dataset at this position and replace the // contents of the view with that element viewHolder.textView.text = dataSet[position] } // Return the size of your dataset (invoked by the layout manager) override fun getItemCount() = dataSet.size } |
activity_main.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"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <!-- A RecyclerView with some commonly used attributes --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/my_recycler_view" android:scrollbars="vertical" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
リスト要素のレイアウト
my_text_view.xml
1 2 3 4 5 6 7 8 9 10 11 |
<?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="wrap_content"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="50dp" /> </LinearLayout> |
gradleの追加設定、バージョンは適宜合わせてください
build.gradle
1 2 3 4 |
dependencies { ... implementation 'androidx.recyclerview:recyclerview:1.2.1' } |
これで、リストのドラッグ&ドロップとスワイプ消去ができました。
ドラッグするときは、
リストのスクロールとの区別のため長押しで機能します。
画像・テキストリストでのItemTouchHelper
前に試した画像を加えた例にItemTouchHelperを追加してみましょう。
MainActivity.kt
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 |
//package your.package.name import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemDecoration import java.util.* import kotlin.collections.ArrayList class MainActivity : AppCompatActivity() { private val names: ArrayList<String> = arrayListOf( "Bellflower", "Bougainvillea", "Cosmos", "Cosmos field", "Delphinium", "Flowers", "Lotus", "Spring Flowers" ) private val photos: ArrayList<Int> = arrayListOf( R.drawable.bellflower, R.drawable.bougainvillea, R.drawable.cosmos, R.drawable.cosmos_field, R.drawable.delphinium, R.drawable.flowers, R.drawable.lotus, R.drawable.spring_flowers ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view) recyclerView.setHasFixedSize(true) val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this) recyclerView.layoutManager = layoutManager // val dataSet: ArrayList<String> = arrayListOf() // var i = 0 // while (i < 20) { // val str: String = java.lang.String.format(Locale.US, "Data_0%d", i) // dataSet.add(str) // i++ // } recyclerView.adapter = MyAdapter(photos, names) val itemDecoration: ItemDecoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL) recyclerView.addItemDecoration(itemDecoration) val adapter = recyclerView.adapter as MyAdapter val mIth = ItemTouchHelper( object : ItemTouchHelper.SimpleCallback( ItemTouchHelper.UP or ItemTouchHelper.DOWN, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT ) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { val fromPos = viewHolder.bindingAdapterPosition val toPos = target.bindingAdapterPosition adapter.notifyItemMoved(fromPos, toPos) return true // true if moved, false otherwise } override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { photos.removeAt(viewHolder.bindingAdapterPosition) names.removeAt(viewHolder.bindingAdapterPosition) adapter.notifyItemRemoved(viewHolder.bindingAdapterPosition) } }) mIth.attachToRecyclerView(recyclerView) } } |
MyAdapter.kt
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 |
//package your.package.name import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class MyAdapter(private val iImages: ArrayList<Int>, private val iNames: ArrayList<String>): RecyclerView.Adapter<MyAdapter.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val textView: TextView val imageView: ImageView init { // Define click listener for the ViewHolder's View. textView = view.findViewById(R.id.text_view) imageView = view.findViewById(R.id.image_view) } } // Create new views (invoked by the layout manager) override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder { // Create a new view, which defines the UI of the list item val view = LayoutInflater.from(viewGroup.context) .inflate(R.layout.my_text_view, viewGroup, false) return ViewHolder(view) } // Replace the contents of a view (invoked by the layout manager) override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) { // Get element from your dataset at this position and replace the // contents of the view with that element viewHolder.imageView.setImageResource(iImages.get(position)) viewHolder.textView.text = iNames[position] } // Return the size of your dataset (invoked by the layout manager) override fun getItemCount() = iNames.size } |
activity_main.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"?> <androidx.constraintlayout.widget.ConstraintLayout 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" tools:context=".MainActivity"> <!-- A RecyclerView with some commonly used attributes --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/my_recycler_view" android:scrollbars="vertical" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> |
my_text_view.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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingStart="20dp" android:paddingTop="5dp" android:baselineAligned="false" tools:ignore="RtlSymmetry,UseCompoundDrawables"> <ImageView android:id="@+id/image_view" android:layout_margin="2dp" android:layout_width="120dp" android:layout_height="120dp" android:contentDescription="@string/description"/> <TextView android:id="@+id/text_view" android:textSize="24sp" android:paddingStart="20dp" android:paddingEnd="10dp" android:paddingTop="50dp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> |
strings.xml
1 2 3 4 |
<resources> <string name="app_name">Your App Name</string> <string name="description">picture</string> </resources> |
build.gradle
1 2 3 4 5 |
... dependencies { ... implementation 'androidx.recyclerview:recyclerview:1.2.1' } |
関連ページ
- RecyclerView の基本的な設定
- RecyclerViewとItemTouchHelperでドラッグ&ドロップ
References:
ItemTouchHelper
リストとカードの作成
ItemTouchHelper.SimpleCallback