지난번에 이어 추가로 2가지 기능을 더 구현했다.
🔗 사과마켓 github
🔗 사과마켓 1탄
선풍기를 없애볼게여 얍!
선풍기 아이템을 길게 누르면 정말로 삭제 하겠냐는 다이얼로그 창이뜹니다. 확인을 누르면 선풍기 항목이 사라진것을 볼 수 있습니다.
LongItemClick 인터페이스는 롱클릭 이벤트를 처리하기 위한 콜백을 정의합니다.
onLongClick(view: View, position: Int) 메서드는 롱클릭한 아이템의 View와 해당 아이템의 위치(position)을 전달받습니다.
interface LongItemClick {
fun onLongClick(view : View, position : Int)
}
var longItemClick : LongItemClick? = null
position이 유효한 범위 내에 있는 경우에만 아이템을 삭제하고 어댑터에게 변경 사항을 알립니다.
fun removeItem(position: Int) {
if (position in 0 until mItems.size) {
mItems.removeAt(position)
notifyItemRemoved(position)
}
}
아이템 롱클릭 이벤트가 발생하면 AlertDialog가 생성됩니다. 확인 버튼을 누르면 removeItem(position) 함수가 호출되어 해당 아이템을 삭제하고 어댑터에게 변경 사항을 알립니다.
adapter.longItemClick = object : MyAdapter.LongItemClick {
override fun onLongClick(view: View, position: Int) {
val alertDialog = AlertDialog.Builder(this@MainActivity)
.setIcon(R.drawable.chat)
.setTitle("삭제")
.setMessage("정말로 삭제하시겠습니까?")
.setPositiveButton("확인") { dialog, which ->
adapter.removeItem(position)
}
.setNegativeButton("취소", null)
.create()
alertDialog.show()
}
}
뒤로가기 버튼 클릭시 메인 엑티비티로 전환되며, 상세페이지는 종료된다.
val backButton = findViewById<ImageButton>(R.id.backButton)
backButton.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
원래 하단 영역의 선들을 xml의 view로 만들어 줬었는데요, 리사이클러뷰의 아이템 데코레이션으로 변경 해주었습니다.
class AddressAdapterDecoration : RecyclerView.ItemDecoration() {
override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDraw(c, parent, state)
val paint = Paint()
paint.color = Color.GRAY
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
val layoutParams = child.layoutParams as RecyclerView.LayoutParams
val top = (child.bottom + layoutParams.bottomMargin + 10).toFloat()
val bottom = top + 1f
val left = parent.paddingStart.toFloat()
val right = (parent.width - parent.paddingEnd).toFloat()
c.drawRect(left, top, right, bottom, paint)
}
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
val offset = 10
outRect.top = offset
outRect.bottom = offset
}
}
onDraw() 함수는 아이템 구분선을 그리는 역할을 합니다. 각 아이템의 하단에 10dp의 추가 간격을 주고, 그 아래에 1dp의 높이로 구분선을 그립니다.
getItemOffsets() 함수는 아이템 간격을 설정하는 역할을 합니다. 각 아이템의 위쪽과 아래쪽에 모두 10dp의 간격을 설정합니다. 매게변수로 아이템 테두리, 데코레이트할 자식 뷰, 해당 데코레이션 클래스를 추가한 리사이클러뷰, 현재 리사이클러뷰의 상태가 있습니다.