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?
Just add String.valueOf():
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{String.valueOf(user.age)}"/>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With