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

纵然是瞬间 提交于 2019-12-19 12:54:32

问题


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:

public class User extends BaseObservable{
        public int age;
        ......


        public User() {}

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
         ...

    }

here is my layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="user" type="com.example.bindingview.User"/>
    </data>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{user.age}"/>
    </LinearLayout>
</layout>

The problem is that TextView cannot have text of age that is int. if I change from int to string of age attribute it worked fine. What should I do to avoid this problem?


回答1:


Just add String.valueOf():

         <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{String.valueOf(user.age)}"/>



回答2:


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>


来源:https://stackoverflow.com/questions/32837455/data-binding-resourcesnotfoundexception-when-attribute-of-object-is-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!