在Android Kotlin中,如果RecyclerView在Fragment中为空,可能是以下几个原因导致的:
private val dataList = mutableListOf()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// 初始化数据源
dataList.add("Item 1")
dataList.add("Item 2")
dataList.add("Item 3")
val view = inflater.inflate(R.layout.fragment_layout, container, false)
// 初始化RecyclerView
val recyclerView = view.findViewById(R.id.recyclerView)
recyclerView.layoutManager = LinearLayoutManager(activity)
recyclerView.adapter = MyAdapter(dataList)
return view
}
class MyAdapter(private val dataList: List) : RecyclerView.Adapter() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = dataList[position]
holder.textView.text = item
}
override fun getItemCount(): Int {
return dataList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textView: TextView = itemView.findViewById(R.id.textView)
}
}
通过以上步骤,你应该能够在Fragment中正确显示RecyclerView的数据了。如果仍然为空,请检查数据源、布局文件和适配器是否设置正确。
上一篇:Android Kotlin Volley同时上传图像和发布其他值?
下一篇:Android kotlin.TypeCastException: null 无法转换为非空类型 com.google.android.gms.maps.SupportMapFragment