2.1 创建一个layout
gradle添加recyclerview的依赖
编写布局文件activity_main
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/forecast_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
初始化recyclerView
//这里使用老的findViewById()的方式
val forecastList = findViewById<RecyclerView>(R.id.forecast_list)
//对象实例化与Java中不同,去掉了new关键字
forecastList.layoutManager = LinearLayoutManager(this)
2.2 创建RecyclerView Adapter
ForecastListAdapter
class ForecastListAdapter(private val items: List<String>) : RecyclerView.Adapter<ForecastListAdapter.ViewHolder>() {
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<RecyclerView>(R.id.forecast_list)
//对象实例化与Java中不同,去掉了new关键字
forecastList.layoutManager = LinearLayoutManager(this)
//又是直接属性调用的方式,真的很赞
forecastList.adapter = ForecastListAdapter(items)
}
}