Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
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
Tags
more
Archives
Today
Total
관리 메뉴

🌱 dreaming DiNO

[kotlin] RecyclerView에 click event 람다함수 콜백하여 데이터 얻어오기 본문

Android/Android Studio

[kotlin] RecyclerView에 click event 람다함수 콜백하여 데이터 얻어오기

MK_____ 2021. 12. 15. 13:20

TODO:: Adapter에서 리사이클러뷰 하나하나 item 클릭 → PhotoCollectionActivity로 값 얻기 필요성

 

1. 클릭하고 처리할 일반함수 or 람다함수를 메인에 추가return 없음(반환x) 걍 토스트

SearchHistory값을 가져와야해서 생성자에 데이터 클래스 SearchHistory를 갖도록 함.

//클릭해서 data를 얻어와야하니 생성자로 SearchHistory를 넣어준다, 글고 토스트로 띄워서 데이터 확인
private fun listItemClicked(searchHistory: SearchHistory){
    Toast.makeText(this,
        "PhotoCollectionActivity - listItemClicked()\n" +
                "term=> ${searchHistory.term}, timestamp=> ${searchHistory.timeStamp}",Toast.LENGTH_LONG).show()
}
// 위와 똑같음
private val listItemClickedLambda: (SearchHistory) -> Unit = {
    Toast.makeText(this,
        "PhotoCollectionActivity - listItemClickedLambda()\n" +
                "term=> ${it.term}, timestamp=> ${it.timeStamp}",Toast.LENGTH_LONG).show()
}

 

2. 어댑터 생성자에 1번 형식의 람다함수를 갖도록 해줌.

호출 해야하니 변수명은 적당히 지어서. 1번과 같은 형식으로 매개변수에 SearchHistory → Unit (반환값x) 

 

3. 어댑터에서 Btn.onClick되었을때 2번에서 만들어준 람다함수 호출 

class SearchHistoryRecyclerAdapter(
    private val clickListner: (SearchHistory) -> Unit) :
    RecyclerView.Adapter<SearchHistoryRecyclerAdapter.SearchHistoryViewHolder>(){

    //SharedPref에 저장된 storedSearchHistoryList 인지, 아니면 그냥 data class SearchHistory?
    val items = SharedPrefManager.getStoreSearchHistoryList() //as ArrayList<SearchHistory>

    //수정 전: 생성자(binding: SearchHistroyItemBinding)
    inner class SearchHistoryViewHolder(private val binding: SearchHistoryItemBinding) : RecyclerView.ViewHolder(binding.root)

    {
        //뷰 가져오기 (뷰바인딩 = xml)

        //search_history_item에 데이터 끼워주기
        fun bindWithView(searchHistoryItem: SearchHistory){
            binding.searchRvTerm.text = searchHistoryItem.term
            binding.searchRvTime.text = searchHistoryItem.timeStamp

            //온클릭리스너 설정
            //TODO:: 정보를 액티비티나 프래그먼트에 알려주기 위해서 콜백함수 필요성!
            binding.constraintSearchItem.setOnClickListener {
                Log.d(TAG, "SearchHistoryRecyclerAdapter : 전체 몸통 클릭됨")
                clickListner(searchHistoryItem)
                Log.d(TAG, "SearchHistoryRecyclerAdapter : value => $searchHistoryItem")
            }

            binding.deleteOneBtn.setOnClickListener {
                Log.d(TAG, "SearchHistoryRecyclerAdapter : 리사이클러뷰 deleteOneBtn 클릭됨!")
            }
        }
    }

 

4. 이 람다함수가 어디서 불렸나 찾아가보니, 액티비티의 어댑터연결해주는 곳이네~!

그리고 자기가 찐으로 불린 람다함수 자리로 감. (1번의 메서드로) 

 

binding.historyRecyclerView.apply {
            layoutManager = LinearLayoutManager(this@PhotoCollectionActivity, VERTICAL, true) //TODO:: 이것도 xml에서 설정해줄 수 있지 않을까?
            //어댑터 설정부분
            adapter = SearchHistoryRecyclerAdapter(clickListner = {
                listItemClicked(it)
                Log.d(TAG, "콜백 받아온 term: ${it.term}, timestamp: ${it.timeStamp}")
            })
            //어댑터 설정부분2 마지막 인자가 람다라면 소괄호 없애고 밖으로 뺄 수 있다
            adapter = SearchHistoryRecyclerAdapter {
                listItemClicked(it)
                Log.d(TAG, "콜백 받아온 term: ${it.term}, timestamp: ${it.timeStamp}")
            }
            // it대신 명시적으로 보여줌
            adapter = SearchHistoryRecyclerAdapter { selectedSearchHistory ->
                listItemClicked(selectedSearchHistory)
                Log.d(TAG, "콜백 받아온 term: ${selectedSearchHistory.term}, timestamp: ${selectedSearchHistory.timeStamp}")
            }
            // it대신 명시적으로 써줬는데, 타입까지 써준 것
            adapter = SearchHistoryRecyclerAdapter { selectedSearchHistory: SearchHistory ->
                listItemClicked(selectedSearchHistory)
                Log.d(TAG, "콜백 받아온 term: ${selectedSearchHistory.term}, timestamp: ${selectedSearchHistory.timeStamp}")
            }


        }

5. 1번 메서드 호출! Baaam~~

 

 

참고 : https://develop-writing.tistory.com/49