databinding 结合RecyclerView 适配器带来的坑 不显示数据

本文介绍了在使用Databinding结合RecyclerView时遇到的一个常见问题,即列表项的数据无法正常显示。原因在于在Adapter的bind()方法中,setText方法设置的文本被布局文件中的Databinding绑定方式覆盖。解决方法是在Adapter中直接对binding变量进行赋值,以确保数据正确显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有一个Recyclerview item布局的显示使用了databinding

item布局类似这样

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>

        <variable
            name="name"
            type="String" />
    </data>

    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:textSize="@dimen/font_size_small"
            android:textColor="@color/white"
            android:gravity="center"
            android:layout_marginBottom="@dimen/dimen_14"
            android:background="@drawable/bg_list_btn"
            android:id="@+id/dept_name"
            android:layout_width="@dimen/dimen_92"
            android:layout_height="@dimen/dimen_20"
            android:text="@{name}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </android.support.constraint.ConstraintLayout>
</layout>

在Adapter的bind()方法中,通过setText方法设置了需要显示的文字。

            @Override
            public void bind(BindViewHolder<DepartmentInfo, ItemAddressBookDeptBinding> viewHolder, int position) {
                viewHolder.getViewDataBinding().deptName.setText(getItem(position).getDeptName());
                }

然而,最终列表显示不出来。

原来布局文件中通过binding的方式设置的文本

android:text="@{name}"

setText方法被这个绑定方法覆盖掉了。

所以在Adapter的bind()方法中改为为binding变量赋值即可

            @Override
            public void bind(BindViewHolder<DepartmentInfo, ItemAddressBookDeptBinding> viewHolder, int position) {
                viewHolder.getViewDataBinding().setName(getItem(position).getDeptName());
                }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值