본문 바로가기

IT개발일지/Android

[Android]꼬뜰린 기초 1. RecyclerView Kotlin 사용하기

* 코틀린 (kotlin)을 사용하여 RecyclerView 세팅해보자.

 

1. recyclerView 설정.

implementation 'com.android.support:recyclerview-v7:28.0.0'

 

2. Adapter 만들기.

class MainRvAdapter (val context: Context, val dogList: ArrayList<Dog>) :
RecyclerView.Adapter<MainRvAdapter.Holder>() {
override fun onBindViewHolder(p0: Holder, position: Int) {
p0?.bind(dogList[position], context)
}

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

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


inner class Holder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
val dogPhoto = itemView?.findViewById<ImageView>(R.id.iv_img)
val dogBreed = itemView?.findViewById<TextView>(R.id.tv_text)
val dogAge = itemView?.findViewById<TextView>(R.id.tv_sub)
//val dogGender = itemView?.findViewById<TextView>(R.id.dogGenderTv)

fun bind (dog: Dog, context: Context) {
if (dog.photo != "") {
val resourceId = context.resources.getIdentifier(dog.photo, "drawable", context.packageName)
dogPhoto?.setImageResource(resourceId)
} else {
dogPhoto?.setImageResource(R.mipmap.ic_launcher)
}
dogBreed?.text = dog.breed
dogAge?.text = dog.age
//dogGender?.text = dog.gender
}
}
}

 

3. Kotlin 파일에 설정하기.

class RecyclerTest : AppCompatActivity() {
/*var dogList = arrayListOf<Dog>()*/

var dogList = arrayListOf<Dog>(
Dog("Chow Chow", "Male", "4", "dog00"),
Dog("Breed Pomeranian", "Female", "1", "dog01"),
Dog("Golden Retriver", "Female", "3", "dog02"),
Dog("Yorkshire Terrier", "Male", "5", "dog03"),
Dog("Pug", "Male", "4", "dog04"),
Dog("Alaskan Malamute", "Male", "7", "dog05"),
Dog("Shih Tzu", "Female", "5", "dog06")
)

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

val mAdapter = MainRvAdapter(this, dogList)
rv_test.adapter = mAdapter

val lm = LinearLayoutManager(this)
rv_test.layoutManager = lm
rv_test.setHasFixedSize(true)
}


}

 

* recycler_view_test.xml 파일은 recyclerView 하나만 세팅이되어있다.

* recycler_item 파일은 위 어뎁터의 변수들을 보고 꾸미면 된다.