글
Kotlin으로 작성된 커스텀 리스트뷰 예제
MainActivity.kt
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val list: ArrayList<CustomItem> = ArrayList()
list.add(CustomItem("James", 23, "Male"))
list.add(CustomItem("Jamie", 20, "Female"))
list.add(CustomItem("John", 30, "Male"))
listview1.adapter = CustomAdapter(this, list)
}
private class CustomAdapter(context: Context, array: ArrayList<CustomItem>): BaseAdapter() {
private var list: ArrayList<CustomItem> = array
private var inflater: LayoutInflater = LayoutInflater.from(context)
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val view: View?
val viewHolder: ViewHolder
if(p1 == null) {
view = this.inflater.inflate(R.layout.listview_item, p2,false)
viewHolder = ViewHolder(view)
view.tag = viewHolder
}
else {
view = p1
viewHolder = view.tag as ViewHolder
}
viewHolder.name.text = list[p0].name
viewHolder.age.text = list[p0].age.toString()
viewHolder.gender.text = list[p0].gender
return view!!
}
override fun getItem(p0: Int): Any {
return list[p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return list.size
}
}
private class ViewHolder(view: View?) {
val name: TextView = view?.findViewById(R.id.nameTextView) as TextView
val age: TextView = view?.findViewById(R.id.ageTextView) as TextView
val gender: TextView = view?.findViewById(R.id.genderTextView) as TextView
}
data class CustomItem(var name: String, var age: Int, var gender: String)
}
listview_item.xml
<?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="match_parent">
<TextView
android:id="@+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<TextView
android:id="@+id/ageTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<TextView
android:id="@+id/genderTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
</LinearLayout>
'Android > Kotlin' 카테고리의 다른 글
Constraint Layout을 이용한 Floating action button Menu 만들기 (0) | 2018.01.09 |
---|---|
Volley를 이용한 간단한 네트워크 통신 (0) | 2017.12.21 |
RECENT COMMENT