안드로이드 프로그래밍[Kotiln Code]/안드로이드 초기 강좌

[안드로이드] 리싸이클러뷰 3 ( 클릭 리스너 등록하기)

훈츠 2020. 4. 13. 15:49
반응형

안녕하세요. 훈츠 입니다. 리싸이클러뷰에 선택이 가능한 클릭 리스너와 tag 연결에 대해 포스팅 합니다. 


리싸이클러 뷰 - 셀렉션 (아이템 선택을 위한 패키지)

안드로이드 리싸이클러뷰에서 지원하고 있는 리싸이클러 뷰 - 셀렉션

▶ 길게 터치할때만 다중선택 가능 합니다. 

 커스터 마이징이 제한됩니다. 

 

추후, 기회가 된다면 포스팅 하도록 하겠습니다. 


bg_item.xml 추가 : 리싸이클러 뷰 체크시 배경화면 변경 

  • Selector : View의 조건에 따라 xml을 참조하여 drawable 을 자동으로 변경해 줌.

  • 색상을 바꿀수 있는 xml 파일을 drawable 폴더에 추가

  • 아이템 상태를 이용해 기능을 추가 : true or false

1

2
3
4
5
6
7
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true" android:drawable="@android:color/holo_blue_bright"/>
    <item android:state_activated="false" android:drawable="@android:color/white"/>
</selector>
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

item_model.xml 추가 : 리싸이클러 뷰의 item

  • item 의 backgroud 에 bg_item 을 선택 합니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_item"  //background 를 bg_item으로 
        android:padding="16dp"
        android:text="TextView" />
</LinearLayout>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

어댑터 세팅 ( Adapter Setting ) 

getItemId 오버라이드 

 

Recycler View의 화면을 클릭 했을때, 해당 포지션의 아이디 값을 받아오기 위해 getItemId( ) 함수를 오버라이드 합니다. id 값이 있다면 id 값을 돌려주고, 없다면 position.toLong() 으로 돌려 줍니다.

1
2
3
4
5
6
7
8
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class DataAdapter(val list:List<Int>,val layout:Int) : RecyclerView.Adapter<DataViewHolder>() {
...
    override fun getItemCount(): Int {
        return list.count()
    }
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

onBindViewHolder 에서 id 값을 View.tag 로 돌려주기

 

holder.containerView.tag 에 ID 값을 돌려 줍니다.

1
2
3
4
5
6
7
8
9
10
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class DataAdapter(val list:List<Int>,val layout:Int) : RecyclerView.Adapter<DataViewHolder>() {
...
    override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
        ...
        holder.containerView.tag = getItemId(position)
        
    }
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

셀렉션 리스트 만들기

 

리싸이클러뷰가 선택 되었을때, 선택 유무를 넣기 위한 셀렉션 리스트를 만듭니다. id가 Long type이기 때문에 Long type으로 만듭니다. 

1
2
3
4
5
6
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class DataAdapter(val list:List<Int>,val layout:Int) : RecyclerView.Adapter<DataViewHolder>() {
    val selectionList = mutableListOf<Long>() //아이디가 롱 타입 입니다. 
...
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

셀렉션 클릭 리스너 만들기

 

  • onItemSelectedListener : ((MutableList<Long>) -> Unit )? = null 
  • onCreateViewHolder 에서 view.setOnClickListener 에 익명함수로 오버라이드 하기 
  • tag 를 이용해서 id 값 가져오기 
  • selectionList 에 id 값이 있다면 삭제하고, 없다면 받아온 id 값을 추가 합니다. 
  • notifyDataSetChanged () 함수를 호출 합니다. 
  • onItemSelectedListener 와 selectionList 를 연결 합니다. 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class DataAdapter(val list:List<Int>,val layout:Int) : RecyclerView.Adapter<DataViewHolder>() {
    val selectionList = mutableListOf<Long>()
    var onItemSelectedListener : ((MutableList<Long>)->Unit)? = null
 
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataViewHolder {
 
        view.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {
                val id = v?.tag
                if(selectionList.contains(id)) selectionList.remove(id)
                else selectionList.add(id as Long)
                notifyDataSetChanged()
                onItemSelectedListener?.let{it(selectionList)}
            }
        })
 
        return DataViewHolder(view)
    }
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

onBindViewHolder 에서 isActivated 에 selectionList 값 돌려주기 

1
2
3
4
5
6
7
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class DataAdapter(val list:List<Int>,val layout:Int) : RecyclerView.Adapter<DataViewHolder>() {
...
    override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
        holder.containerView.tag = getItemId(position)
        holder.containerView.isActivated = selectionList.contains(getItemId(position))
    }
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

전체 코드

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
31
32
33
34
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class DataAdapter(val list:List<Int>,val layout:Int) : RecyclerView.Adapter<DataViewHolder>() {
    val selectionList = mutableListOf<Long>()
    var onItemSelectedListener : ((MutableList<Long>)->Unit)? = null
 
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataViewHolder {
 
        view.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {
                val id = v?.tag
                if(selectionList.contains(id)) selectionList.remove(id)
                else selectionList.add(id as Long)
                notifyDataSetChanged()
                onItemSelectedListener?.let{it(selectionList)}
            }
        })
        return DataViewHolder(view)
    }
 
    override fun getItemCount(): Int {
        return list.count()
    }
 
    override fun getItemId(position: Int): Long {
        return position.toLong()
    }
 
    override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
        holder.containerView.textView.text = list[position].toString()
        holder.containerView.tag = getItemId(position)
        holder.containerView.isActivated = selectionList.contains(getItemId(position))
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

MainActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class MainActivity : AppCompatActivity() {
    val listData = (0..100).toList().shuffled()
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val adapter = DataAdapter(listData,R.layout.item_model)
        adapter.onItemSelectedListener = {
            println("선택된 id : $it")
        }
 
        intlist.adapter = adapter
        intlist.layoutManager = LinearLayoutManager(this,RecyclerView.VERTICAL,false)
 
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

코드 실행

https://youtu.be/Tw1Q8dncpoQ

 

반응형