Data Binding : Resources$NotFoundException when attribute of object is int

后端 未结 2 955
南方客
南方客 2021-01-07 23:29

I am trying to use Data binding. It is work properly if I use object that has attribute of string, but in this case I use int and it doesn\'t work. I have object User:

相关标签:
2条回答
  • 2021-01-08 00:10

    Just add String.valueOf():

             <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@{String.valueOf(user.age)}"/>
    
    0 讨论(0)
  • 2021-01-08 00:16

    Its too late to explain it. But may be it helps someone in future.
    We Cant set a value to TextView other than String
    Android Data binding implementation class try to set the value of int to the textview which leads to resource not found exception with this method setText(int).

    So to set a int value or value with data type other than String we need to convert it to String first then set the value to the textview.
    There are so many ways of converting values to Strings like one mention above or you may concatenate it with grave accent (`) as

    android:text="@{` ` + user.age}"
    



    or may use string resource value to do so

    android:text="@{@string/age(user.age)}"
    

    and then in string.xml file declare this string resource value as

    <string name="age">%d</string>
    
    0 讨论(0)
提交回复
热议问题