recyclerview上没有显示任何项目



我正在从一个api中获取数据,并将其显示在回收视图中。我已经检查了许多关于同一问题的其他查询,但我似乎找不到解决这个问题的方法。

下面是我的活动类

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retrofit = RetrofitClient.instance
jsonApi = retrofit.create(MyApi::class.java)
fetchRecyclerData()
}
private fun fetchRecyclerData() {
compositeDisposable?.add(jsonApi.posts
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe{posts->displayData(posts)})
}
private fun displayData(posts: List<Post>?) {
val adapter = PostAdapter(this,posts!!)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
adapter.notifyDataSetChanged()
}
}

下面是我的适配器

class PostAdapter(internal var context: Context, internal var 
postList:List<Post>):RecyclerView.Adapter<PostViewHolder>()
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.post_layout,parent,false)
return PostViewHolder(itemView)
}
override fun onBindViewHolder(holder: PostViewHolder, position: Int) {
holder.tvAuthor.text = postList[position].userId.toString()
holder.tvContent.text = StringBuilder(postList[position].body.substring(0,20))
.append("...").toString()
holder.tvTitle.text = postList[position].title
}
override fun getItemCount(): Int {
return postList.size
}
}

Logcat

06-17 13:29:06.047 23952-23952/com.malikali.kotlinxrxjava2xretrofit2 W/RecyclerView: No adapter attached; skipping layout
06-17 13:29:06.057 23952-23952/com.malikali.kotlinxrxjava2xretrofit2 W/RecyclerView: No adapter attached; skipping layout

下面是我的xml文件。我仍然不明白在这种情况下做错了什么。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

提交数据后,您应该始终在适配器上调用notifyDataSetChanged(),因此更改代码如下:

private fun displayData(posts: List<Post>?) {
val adapter = PostAdapter(this,posts!!)
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
adapter.notifyDataSetChanged()

}

还请分享您的xml。三种可能的条件1:回收器视图的高度或宽度必须为02:"帖子"列表为空3:在订阅中记录日志,看看是否没有抛出任何异常,否则实现rxjava的错误,以检查可能的异常

相关内容

  • 没有找到相关文章

最新更新