2.0 编写你的第一个类

2.1 创建一个layout

gradle添加recyclerview的依赖
编写布局文件activity_main



    


初始化recyclerView

        //这里使用老的findViewById()的方式
        val forecastList = findViewById(R.id.forecast_list)
        //对象实例化与Java中不同,去掉了new关键字
        forecastList.layoutManager = LinearLayoutManager(this)

2.2 创建RecyclerView Adapter

ForecastListAdapter

class ForecastListAdapter(private val items: List) : RecyclerView.Adapter() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(TextView(parent.context))
    }

    override fun getItemCount(): Int = items.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        //直接属性调用的方式,很赞
        holder.textView.text = items[position]
    }

    class ViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)
}

调用adapter

class MainActivity : AppCompatActivity() {
    //创建List的方式
    private val items = listOf(
            "Mon 6/23 - Sunny - 31/17",
            "Tue 6/24 - Foggy - 21/8",
            "Wed 6/25 - Cloudy - 22/17",
            "Thurs 6/26 - Rainy - 18/11",
            "Fri 6/27 - Foggy - 21/10",
            "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
            "Sun 6/29 - Sunny - 20/7"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //这里使用老的findViewById()的方式
        val forecastList = findViewById(R.id.forecast_list)
        //对象实例化与Java中不同,去掉了new关键字
        forecastList.layoutManager = LinearLayoutManager(this)
        //又是直接属性调用的方式,真的很赞
        forecastList.adapter = ForecastListAdapter(items)
    }
}

你可能感兴趣的:(2.0 编写你的第一个类)