20230906 longClick

기메단·2023년 9월 6일
0

TIL

목록 보기
36/44

LongClick 했을 때 다이얼로그를 띄우면서 리싸이클러뷰의 아이템 리스트를 삭제 시켜보자.

MyAdapter

class MyAdapter(val mItems:MutableList<MyItem>) : RecyclerView.Adapter<MyAdapter.Holder>() {

    interface ItemLongClick {
        fun onLongClick(view: View, position: Int)
    }
        var itemLongClick: ItemLongClick? = null

override fun onBindViewHolder(holder: MyAdapter.Holder, position: Int) {
        holder.iconImageView.setImageResource(mItems[position].aIcon)

        // 2초간 클릭했을 때 삭제
        val longClick = android.os.Handler()
        holder.itemView.setOnLongClickListener {
            longClick.postDelayed({
                itemLongClick?.onLongClick(it, position)
            }, 2000)
            true
        }
}
      

MainActivity

    class MainActivity : AppCompatActivity() {

        private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(binding.root)
            
                        binding.recyclerView.adapter = MyAdapter(dataList)

            val adapter = MyAdapter(dataList)
            binding.recyclerView.adapter = adapter
            binding.recyclerView.layoutManager = LinearLayoutManager(this)
            
            // 삭제 다이얼로그
            adapter.itemLongClick = object : MyAdapter.ItemLongClick {
                override fun onLongClick(view: View, position: Int) {
                    val itemRomove = dataList[position]
                    AlertDialog.Builder(this@MainActivity)
                        .setTitle("삭제")
                        .setMessage("삭제하시겠습니까?")
                        .setPositiveButton("삭제") { dialog, _ ->
                            dataList.remove(itemRomove)
                            adapter.notifyDataSetChanged()
                            dialog.dismiss()
                        }
                        .setNegativeButton("취소") { dialog, _ ->
                            dialog.dismiss()
                        }
                        .show()
                }
            }

상세 페이지에서 뒤로가기 버튼도 구현했다.

DetailActivity

class DetailActivity : AppCompatActivity() {

    private val binding by lazy { ActivityDetailBinding.inflate(layoutInflater) }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        
 binding.backBtn.setOnClickListener {
            finish()
 		}
     }
}

0개의 댓글