프로그래밍/Android

[Android] RecyclerView 사용하기

흔한티벳여우 2020. 9. 17. 18:28
반응형

먼저 RecyclerView의 장점들을 설명하고 싶으나, 정말 많은 블로그에서 설명하고 있음으로 패스.

 

빠르게 구현하는 방법에 대해 배워보겠다.

일단 RecyclerView에 사용할 SubitemView를 만들어보겠다.

layout/recycler_factory_item.xml 을 생성한다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/btn_item_delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="#ffffff"
        android:src="@drawable/ic_baseline_delete_24"
        app:fabSize="mini"
        app:borderWidth="0dp"
        app:elevation="0dp"
        app:layout_constraintBottom_toBottomOf="@+id/tv_item_ip"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/tv_item_name" />
    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/tv_item_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Factory Name"
        android:textSize="20sp"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/btn_item_delete"
        app:layout_constraintTop_toTopOf="parent"
        />
    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/tv_item_ip"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="192.168.123.111"
        android:textSize="16sp"
        android:paddingLeft="20dp"
        android:paddingBottom="10dp"
        app:layout_constraintTop_toBottomOf="@id/tv_item_name"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/btn_item_delete"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

위의 코드의 랜더링

이제 activity_main,xml에 위에서 만든 layout을 이용하여 recyclerView를 선언해주자.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_write_factoryList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        tools:listitem="@layout/recycler_factory_item"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

 

RecyclerView에 표현할 내용은 공장 정보와 그에 해당하는 IP 정보임으로 이를 위한 data class를 선언해주겠다.

data class Factory (
    var Name: String,
    var Ip: String = ""
)

 

RecyclerView를 사용하려면 Adapter를 우리가 구현해줘야 한다. (귀찮...)

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.recycler_factory_item.view.*

class RecyclerFactoryAdapter(var factoryList: MutableList<Factory>) : RecyclerView.Adapter<RecyclerFactoryAdapter.ViewHolder>() {

    inner class ViewHolder(
        itemView: View
    ) : RecyclerView.ViewHolder(itemView)
    {
        var currentFactory : Factory? = null
        var currentPosition : Int = 0

        fun setData(facotry: Factory?, pos: Int){
            if (facotry != null){
                itemView.tv_item_name.text = facotry.Name
                itemView.tv_item_ip.text = facotry.Ip
                currentFactory = facotry
                currentPosition = pos
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val context = parent.context
        val view = LayoutInflater.from(context).inflate(R.layout.recycler_factory_item, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return factoryList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.setData(factoryList[position], position)
        holder.itemView.btn_item_delete.setOnClickListener {
            removeItem(position)
        }
    }

    fun removeItem(position: Int){
        factoryList.removeAt(position)
        notifyItemRemoved(position)
        notifyItemRangeChanged(position, factoryList.size)
    }
}

내부에서 각각의 SubItemView를 핸들링하는 방법을 보여주기 위해 delete기능을 추가해보았다.

 

이제 MainActivity.kt에서 우리가 만든 Adapter와 RecyclerView를 연결해보자.

class MainActivity : AppCompatActivity() {

    private var factorySetupDataList = mutableListOf<Factory>()

    private lateinit var recyclerFactoryAdapter : RecyclerFactoryAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        factorySetupDataList.add(Factory("Factory 1","192.168.111.111"))
        factorySetupDataList.add(Factory("Factory 2","192.168.111.112"))
        factorySetupDataList.add(Factory("Factory 3","192.168.111.113"))
        
        recyclerFactoryViewSetting()
    }

    private fun recyclerFactoryViewSetting(){
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL

        rv_write_factoryList.layoutManager = layoutManager

        recyclerFactoryAdapter = RecyclerFactoryAdapter(factorySetupDataList)
        rv_write_factoryList.adapter = recyclerFactoryAdapter
    }    
}

 

자 완성!!

반응형