Kotlin实现recycleview

导入依赖:

  implementation "androidx.recyclerview:recyclerview:1.1.0"
    implementation "androidx.cardview:cardview:1.0.0"

activity:

package com.example.zkotlin

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_weather.*

class WeatherActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_weather)
        val examplelist = generateDummyList(50)
        recycler_view.adapter = ExampleAdapter(examplelist)
        recycler_view.layoutManager = LinearLayoutManager(this)
        recycler_view.setHasFixedSize(true)
    }

    private fun generateDummyList(size: Int): List {
        val list = ArrayList()
        for (i in 0 until size) {
            val drawable = when (i % 3) {
                0 -> R.drawable.ic_android
                1 -> R.drawable.ic_audio
                2 -> R.drawable.ic_sun
                else -> R.mipmap.ic_launcher
            }
            val item = ExampleItem(drawable, "Item $i", "Line 2 ")
            list += item
        }
        return list
    }
}

数据类:

package com.example.zkotlin

data class ExampleItem(val imageResuorce: Int, val text1: String, val text2: String)

适配器:

package com.example.zkotlin

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.example_item.view.*

class ExampleAdapter(private val exampleList: List) :
    RecyclerView.Adapter() {


    class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.image_view
        val textView1: TextView = itemView.text_view_1
        val textView2: TextView = itemView.text_view_2
    }

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

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

    override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
        val currentItem = exampleList[position]
        holder.imageView.setImageResource(currentItem.imageResuorce)
        holder.textView1.text = currentItem.text1
        holder.textView2.text = currentItem.text2
    }

}

activity布局:




    

item布局:




    

        

        


        

    

效果图:

 

Kotlin实现recycleview_第1张图片

 

你可能感兴趣的:(kotlin学习)