安卓开发 原生View 帮我写完整kotlin 代码 垂直recyclerview 嵌套水平recyclerview
时间: 2024-03-01 21:55:15 浏览: 80
Kotlin实现Android RecyclerView
5星 · 资源好评率100%
好的,以下是完整的 Kotlin 代码:
```kotlin
class MainActivity : AppCompatActivity() {
private lateinit var mRecyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mRecyclerView = findViewById(R.id.verticalRecyclerView)
mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
mRecyclerView.adapter = VerticalAdapter()
}
inner class VerticalAdapter : RecyclerView.Adapter<VerticalAdapter.VerticalViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VerticalViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_vertical, parent, false)
return VerticalViewHolder(view)
}
override fun onBindViewHolder(holder: VerticalViewHolder, position: Int) {
holder.mHorizontalRecyclerView.layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false)
holder.mHorizontalRecyclerView.adapter = HorizontalAdapter()
}
override fun getItemCount(): Int {
return 10
}
inner class VerticalViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val mHorizontalRecyclerView: RecyclerView = itemView.findViewById(R.id.horizontalRecyclerView)
}
}
inner class HorizontalAdapter : RecyclerView.Adapter<HorizontalAdapter.HorizontalViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HorizontalViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_horizontal, parent, false)
return HorizontalViewHolder(view)
}
override fun onBindViewHolder(holder: HorizontalViewHolder, position: Int) {
holder.mTextView.text = (position + 1).toString()
}
override fun getItemCount(): Int {
return 5
}
inner class HorizontalViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val mTextView: TextView = itemView.findViewById(R.id.textView)
}
}
}
```
这段代码实现了一个垂直的 RecyclerView,其中每个 item 包含一个水平的 RecyclerView。其中 VerticalAdapter 是垂直 RecyclerView 的适配器,HorizontalAdapter 是水平 RecyclerView 的适配器。VerticalViewHolder 中包含了一个水平 RecyclerView,HorizontalViewHolder 中包含了一个 TextView。
阅读全文