我知道这个问题已经被提出,但是我尝试了他们提出的所有解决方案,但没有任何效果。我在主线程中创建了适配器,在onCreate函数中添加了适配器,但仍然无法正常工作。在结束我的问题之前,请查看我的代码并告诉我我在做什么错。
class PostsActivity : AppCompatActivity() {
var recyclerView: RecyclerView? = null
var postObjList : ArrayList<PostObj>? = null
var postContentList : ArrayList<PostContentObj>? = null
var viewModel : PostsViewModel? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_posts)
initRecyclerView()
viewModel = PostsViewModel(recyclerView!!, postObjList!!, postContentList!!)
val activityPostsBinding: ActivityPostsBinding =
DataBindingUtil.setContentView(this, R.layout.activity_posts)
activityPostsBinding.viewModel = viewModel
viewModel!!.loadIdList()
}
private fun initRecyclerView() {
recyclerView = findViewById(R.id.posts_recycler_view)
postObjList = ArrayList()
postObjList!!.add(PostObj("a", "a", "a", "a", "a"))
postContentList = ArrayList()
recyclerView!!.adapter = PostsAdapter(this, postObjList!!, postContentList!!)
recyclerView!!.layoutManager = LinearLayoutManager(this)
}
}
class PostsAdapter(val context: Context, val posts: ArrayList<PostObj>, val postsContent: ArrayList<PostContentObj>) : RecyclerView.Adapter<PostsAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.single_post_layout, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentPostObj = posts.get(position)
holder.publisher.text = currentPostObj.publisher
}
override fun getItemCount(): Int {
return posts.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val publisher : TextView = itemView.findViewById(R.id.post_publisher)
val parentLayout : RelativeLayout = itemView.findViewById(R.id.parent_layout)
}
}
我在做什么错?我查看了其他帖子中的其他答案,但仍然无法使它起作用。 这是我正在看的帖子 The post
答案 0 :(得分:0)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activityPostsBinding: ActivityPostsBinding =
DataBindingUtil.setContentView(this, R.layout.activity_posts)
// replaced setContentView with above line
// this way recyclerView = findViewById(R.id.posts_recycler_view) is correct view
initRecyclerView()
viewModel = PostsViewModel(recyclerView!!, postObjList!!, postContentList!!)
activityPostsBinding.viewModel = viewModel
viewModel!!.loadIdList()
}
您收到此错误是因为setContentView(R.layout.activity_posts)
中同时有DataBindingUtil.setContentView(this, R.layout.activity_posts)
和onCreate
,所以当您从recyclerView
获得findViewById(R.id.posts_recycler_view)
时,可能会得到错误的recyclerView。 / p>