Kotlin开发Android时RecyclerView添加条目成功但文本不显示问题求助
问题原因定位
- onBindViewHolder绑定逻辑错误:你在绑定数据时重新inflate了一个全新的
AgentDetailsBinding实例,这个实例对应的View没有挂载到holder的itemView上,你给binding.tvAttribute设置的文本根本不会显示到实际渲染的条目上。 - RecyclerView高度约束缺失:你给
rvAgentAttributes设置的高度是0dp,但只配置了top约束,没有配置bottom约束,会导致RecyclerView高度为0,就算条目内容正常也无法显示。 - ViewHolder没有持有Binding实例:标准ViewBinding结合RecyclerView的实现需要让ViewHolder持有对应条目的Binding对象,既能避免重复inflate消耗性能,也能保证绑定的View和渲染的View一致。
修复方案
1. 修复activity_main.xml中RecyclerView的约束
给RecyclerView添加底部约束,保证高度正常撑满可用空间:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/rvAgentAttributes" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/etSearch" <!-- 新增下面这行约束 --> app:layout_constraintBottom_toBottomOf="parent" />
2. 重构AgentAttributesAdapter实现
修改适配器逻辑,让ViewHolder持有条目Binding,直接复用绑定的View设置内容:
class AgentAttributesAdapter(private val agent_attributes: MutableList<AgentAttributes>) : RecyclerView.Adapter<AgentAttributesAdapter.AgentViewHolder>() { // ViewHolder直接持有条目的Binding实例 inner class AgentViewHolder(val binding: AgentDetailsBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AgentViewHolder { val binding = AgentDetailsBinding.inflate(LayoutInflater.from(parent.context), parent, false) return AgentViewHolder(binding) } override fun onBindViewHolder(holder: AgentViewHolder, position: Int) { val currentAgent = agent_attributes[position] // 直接通过holder持有的binding设置文本 holder.binding.tvAttribute.text = currentAgent.Name // 如需展示Value属性可新增下面这行 // holder.binding.tvValue.text = currentAgent.Value } override fun getItemCount(): Int = agent_attributes.size fun addAttributes(attr:AgentAttributes){ agent_attributes.add(attr) notifyItemInserted(agent_attributes.size - 1) } }
可选校验项
检查你的agent_details.xml布局中tvAttribute控件的配置,确认文本颜色和条目背景色不一致,同时控件宽高没有设置为0。
内容的提问来源于stack exchange,提问作者joel lopez
相关产品推荐
相关产品推荐

