我正在Recycleview
中创建自定义Kotlin
我没有在代码中得到任何异常,它运行得很完美,但关注的是项目没有出现在Recycleview
beacuase上,代码在Adapter类中无法访问。
Waring: -
RecycleView
适配器的重写方法上无法访问的代码。
请检查我的适配器和活动类
适配器类
class CustomRecycleAdapter(val data: ArrayList<String>) : RecyclerView.Adapter<CustomRecycleAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
val v = LayoutInflater.from(parent?.context).inflate(R.layout.recycle_item, parent, false)
return ViewHolder(v)
}
override fun getItemCount(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
return data.size;
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
val item = data[position]
println("Data is here==>>> "+item)
holder?.textViewName?.text = item;
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val textViewName = itemView.findViewById<TextView>(R.id.tvName)
}
}
活动类
class FirstRecycleViewExample : AppCompatActivity() {
val data = arrayListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.first_recycleview)
val recycler_view = findViewById<RecyclerView>(R.id.recycler_view)
data.add("First Data")
data.add("Second Data")
data.add("Third Data")
data.add("Forth Data")
data.add("Fifth Data")
//creating our adapter
val adapter = CustomRecycleAdapter(data)
//now adding the adapter to recyclerview
recycler_view.adapter = adapter
}
}
答案 0 :(得分:2)
您还没有为RecyclerView添加布局管理器。只需添加LinearLayoutManager
或GridLayoutManager
recycler_view.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
答案 1 :(得分:1)
使用TODO函数,您的代码将不会基于您运行
查看kotlin网站以获取更多详细信息,TODO function
除非您将其删除或注释掉,否则它将始终抛出异常
要验证答案,请检查您的日志消息并对照TODO中设置的消息交叉引用错误消息
如果这不是问题,那么很可能您尚未将recycle_view.layoutManager设置为LinearLayoutManager,GridLayoutManager等。
这将在您在主UI上显示回收视图时将内容布局设置为的类中完成。 setContentView(R.layout.activity_main)
希望这会有所帮助:)