【发布时间】:2021-01-31 02:43:30
【问题描述】:
我有一个片段,它位于具有回收器视图的视图寻呼机内。尽管实际上调用了 onbindviewholder,但我的回收站视图上的项目没有显示,我一直遇到这样的问题。我不知道可能是什么问题。
这是我的片段的 XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_dishes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:listitem="@layout/dish_rv_item"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
这是我的片段的代码:
class CategoryFragment(val dishes: ArrayList<Dish>):Fragment() {
private val binding by viewBinding(CategoryFragmentBinding::bind)
private val rvAdapter by lazy {
CategoryRecyclerAdapter()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = CategoryFragmentBinding.inflate(inflater,container,false)
return view.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setUpRecyclerView()
rvAdapter.addAll(dishes)
}
private fun setUpRecyclerView(){
val linearLayoutManager = LinearLayoutManager(activity)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
binding.rvDishes.layoutManager = linearLayoutManager
binding.rvDishes.adapter = rvAdapter
}
companion object{
fun newInstance(dishes:ArrayList<Dish>) = CategoryFragment(dishes)
}
}
最后是我的适配器的代码:
class CategoryRecyclerAdapter(private val dishes:ArrayList<Dish> = ArrayList()): RecyclerView.Adapter<CategoryRecyclerAdapter.ViewHolder>() {
fun addAll(list: List<Dish>){
dishes.clear()
list.forEach {
dishes.add(it)
}
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.dish_rv_item,parent,false)
val binding = DishRvItemBinding.bind(view)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
Log.d("TAG", "binding view holder")
holder.bindView(dishes[position])
}
override fun getItemCount(): Int = dishes.size
inner class ViewHolder(private val binding: DishRvItemBinding):RecyclerView.ViewHolder(binding.root){
fun bindView(dish: Dish){
binding.apply {
tvDishName.text = dish.name
}
}
}
}
我已经检查了我的项目列表不为空,项目计数不为 0,我已将我的回收站视图的布局高度和宽度更改为 0dp,匹配父项并包装内容。我调试了它并调用了 bindView 方法,但我只得到一个空屏幕,正如您在此处看到的那样:
感谢任何帮助!
【问题讨论】:
-
您检查过您的 tvDishName 视图可见性吗?
-
请同时分享您的 ViewPager 适配器源代码和
dish_rv_item.xml代码,有可能是项目布局和适配器问题 -
尝试在开发者选项中显示布局边界,看看是否真的添加了视图...
标签: android kotlin android-recyclerview android-constraintlayout android-viewbinding