优秀文章:一份关于 Java、Kotlin 与 Android 的学习笔记
一,实体类的编写,使用data关键字,就可以自动实现equals()、hashCode()、toString(),get(),set()方法
data class DateBean(
var name : String ,
val age :Int ,
var money : Double,
var isChecked : Boolean)
二,在Activity中使用. 创建对象不再需要new,
1,var代表变量,val代表常量
2,不需要findbyid,(通过apply plugin: 'kotlin-android-extensions'插件即可实现)
class KottlinActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin2)
initData()
initUI()
}
val dateBeans = ArrayList<DateBean>()
private fun initData() {
for (i in 0..19) {
val dateBean = DateBean("张三" + i, i, 10000.45,false)
dateBeans.add(dateBean)
}
}
private fun initUI() {
val machinePointAdapter = MachinePointAdapter(dateBeans)
recyclerView.adapter = machinePointAdapter
//自己写的接口回调
machinePointAdapter.setOnItemClickListener(object : MachinePointAdapter.OnClickItemListener {
override fun onClickItemListener(dataBeans: List<DateBean>, position: Int) {
Toast.makeText(applicationContext, dataBeans!![position].name, Toast.LENGTH_SHORT).show()
}
})
}
}
三,适配器的实现
class MachinePointAdapter(dateBeans: ArrayList<DateBean>) : RecyclerView.Adapter<MachinePointAdapter.MachineHolder>() {
private var listener: OnClickItemListener? = null
val dataBeans = dateBeans;
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MachineHolder {
return MachineHolder(LayoutInflater.from(parent!!.context).inflate(R.layout.item_machine, null))
}
override fun onBindViewHolder(holder: MachineHolder?, position: Int) {
holder?.itemView?.machine_number?.text = dataBeans[position].age.toString()
holder?.itemView?.machine_address?.text = dataBeans[position].name
holder?.itemView.setOnClickListener { listener?.onClickItemListener(dataBeans,position) }
}
override fun getItemCount(): Int {
return if (dataBeans.size != 0) {
dataBeans.size
} else 0
}
inner class MachineHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {}
interface OnClickItemListener {
fun onClickItemListener(dataBeans: List<DateBean>, position: Int)
}
fun setOnItemClickListener(listener: OnClickItemListener?) {
this.listener = listener
}
}