개발일지

Android in A..Z - RecyclerView (Selection - Observer) 본문

Android (안드로이드)/RecyclerView

Android in A..Z - RecyclerView (Selection - Observer)

강태종 2021. 1. 15. 04:32

SelectionObserver

Selection에 Observer을 통해 콜백 함수를 작성할 수 있다.

Selection이 되면 Delete Option Menu가 생기는 예제이다.

addObserver(object : SelectionTracker.SelectionObserver<Long>() {
                    override fun onSelectionChanged() {
                        super.onSelectionChanged()
                        val tracker = this@apply
                        if (tracker.hasSelection() && menu.findItem(MENU_DELETE) == null) {
                            menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, "Delete")
                                    .setIcon(R.drawable.ic_delete)
                                    .setOnMenuItemClickListener {
                                        tracker.selection.forEach {
                                            val holder = recyclerView.findViewHolderForItemId(it)
                                            if (holder is SelectionAdapter.SelectionHolder) {
                                                list.remove(holder.element)
                                            }
                                        }

                                        tracker.clearSelection()
                                        adapter.notifyDataSetChanged()
                                        true
                                    }
                                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
                        } else if (!tracker.hasSelection() && menu.findItem(MENU_DELETE) != null){
                            menu.removeItem(MENU_DELETE)
                        }
                    }
                })
  • onSelectionChanged : Selection에 변화가 있을 때 호출된다.


Git (예제코드)

github.com/KangTaeJong98/Example/tree/main/Android/RecyclerView

 

KangTaeJong98/Example

My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.

github.com

 

Comments