我有一个问题:
RecyclerView:未连接适配器;跳过布局
由于列表尚未准备好,所以无法在OnCreate
中定义适配器。
如何在OnCreate
中定义适配器?或解决我的问题的可能解决方案是什么?
答案 0 :(得分:0)
在onCreate中,我做到了:
adapter = MyAdapter(this@MyActivity)
adapter.data = ArrayList()
然后,我刚刚设置了adapter.date = xxx
在我的适配器中,我有:
class MyAdapter(val activity: MyActivity) :
RecyclerView.Adapter<MyAdapter.BodyViewHolder>() {
var data: MutableList<MyModel>? = null
set(value) {
field = value
notifyDataSetChanged()
}
override fun getItemCount() = data?.size ?: 0
fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View {
return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BodyViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.my_layout, parent, false)
return BodyViewHolder(view)
}
override fun onBindViewHolder(holder: BodyViewHolder, position: Int) {
holder.bindValue(data?.get(position), activity)
}
class BodyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindValue(record: MyModel?, activity: MyActivity) {
record?.let {
itemView.mTextView.text = ....
}
}
}
}
值得一提的是,我的回收站视图的高度为wrap_content
<android.support.v7.widget.RecyclerView
android:id="@+id/mRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
答案 1 :(得分:0)
如果onCreate
中没有数据,那完全可以。您需要做的是定义适配器并将其与您的RecyclerView
绑定。准备好数据后,将数据添加到adapter
中的列表中并进行通知。示例如下
class MyAdapter: RecyclerView.Adapter<MyViewHolder>() {
private val data = mutableListOf<MyModel>()
override fun getItemCount() = data.count()
fun addData(data : MyModel) {
// add single data the list or call addAll() to add a group of data.
// just remember not to replace the variable
}
fun clearData() {
}
fun deleteData(id: Int) {
}
}