이번 시간에는 다중 선택에 이어서 다중 삭제하는 방법에 대하여 알아보겠습니다.
이전 포스팅에 이어서 하니 아래 포스팅을 먼저 보시고 오시면 됩니다.
2022.09.22 - [안드로이드] - [안드로이드 코틀린] RecyclerView 다중 선택 색상 변경하는 방법
- 설명 -
1. 다중 선택된 아이템 삭제하는 Button
2. android:layout_weight
레이아웃 비율 설정
3. android:layout_centerInParent="true"
부모 창 정중앙에 위치
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2">
<Button
android:id="@+id/deleteBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="삭제"/>
</RelativeLayout>
</LinearLayout>
- 설명 -
1. itemList, adapter 전역 변수로 변경
2. deleteItem()
선택된 아이템 삭제하는 함수
3. for( (index, item) in itemList.withIndex().reversed())
index: 위치 값
item: 데이터
itemList.withIndex().reversed(): 위치 값 역순
class MainActivity : AppCompatActivity() {
private lateinit var itemList: ArrayList<Item>
private lateinit var adapter: ItemAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//초기화
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
adapter = ItemAdapter(getData())
//recyclerView 설정
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
val deleteBtn: Button = findViewById(R.id.deleteBtn)
//삭제 이벤트
deleteBtn.setOnClickListener {
//아이템 삭제
deleteItem()
}
}
@SuppressLint("NotifyDataSetChanged")
private fun deleteItem(){
//리스트에서 선택된 아이템 삭제( index: 위치값, item: 아이템)
//withIndex.reversed: 역순
for( (index, item) in itemList.withIndex().reversed()){
//아이템 담기
val item: Item = item
//아이템이 선택되었다면
if(item.selected){
//해당 아이템 삭제
itemList.removeAt(index)
}
}
//적용
adapter.notifyDataSetChanged()
}
/**
* 데이터 생성
*/
private fun getData(): ArrayList<Item>{
itemList = ArrayList()
for( index in 1..10){
itemList.add(Item("$index 번째 아이템", false))
}
return itemList
}
}
2022.09.21 - [안드로이드] - [안드로이드 코트린] SharedPreferences 간단한 데이터 저장하는 방법
2022.09.20 - [안드로이드] - [안드로이드 코틀린] 코드(MainActivity)에서 배경 색상 바꾸는 다양한 방법
2022.09.13 - [안드로이드] - [안드로이드 코틀린] 액티비티(Activity) 뒤로 가기 버튼 만드는 방법
[안드로이드 코틀린] Vibrator 진동 효과 내는 방법 (0) | 2022.09.27 |
---|---|
[안드로이드 코틀린] Ringtone 효과음 내는 방법 (0) | 2022.09.26 |
[안드로이드 코틀린] RecyclerView 다중 선택 색상 변경하는 방법 (2) | 2022.09.22 |
[안드로이드 코틀린] SharedPreferences 간단한 데이터 저장하는 방법 (0) | 2022.09.21 |
[안드로이드 코틀린] 코드(MainActivity) 에서 배경 색상 바꾸는 다양한 방법 (0) | 2022.09.20 |
댓글 영역