在Android Kotlin中,在Fragment中创建RecyclerView可以通过以下步骤解决:
data class Person(val name: String, val age: Int)
class PersonAdapter(private val personList: List) :
RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PersonViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_person, parent, false)
return PersonViewHolder(view)
}
override fun onBindViewHolder(holder: PersonViewHolder, position: Int) {
val person = personList[position]
holder.bind(person)
}
override fun getItemCount(): Int {
return personList.size
}
inner class PersonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(person: Person) {
itemView.findViewById(R.id.nameTextView).text = person.name
itemView.findViewById(R.id.ageTextView).text = person.age.toString()
}
}
}
class MyFragment : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: PersonAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_my, container, false)
recyclerView = view.findViewById(R.id.recyclerView)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val personList = listOf(
Person("John", 25),
Person("Jane", 30),
Person("Mike", 35)
)
adapter = PersonAdapter(personList)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(activity)
}
}
在这个示例中,我们创建了一个PersonAdapter来将数据绑定到RecyclerView上,并在Fragment中初始化了RecyclerView和适配器。在onViewCreated方法中,我们为RecyclerView设置布局管理器和适配器。
请注意,我们还需要在布局文件中创建一个用于显示个人信息的item_person.xml布局,例如:
这样,当Fragment被创建时,RecyclerView将显示一个包含Person对象信息的列表。