Android 数据绑定@BindingConversion 失败,int 到字符串 [英] Android Data Binding @BindingConversion failure for int to string
问题描述
在尝试将 int 转换为字符串的 @BindingConversion 时遇到了一个神秘问题.
以下代码适用于浮点数到字符串:
Ran into a mysterious problem when trying to make a @BindingConversion for int to string.
The following code works for floats to strings:
xml:
...
<variable
name="myViewModel"
type="... .SomeModel" />
...
<TextView
style="@style/StyleStuff"
android:text="@{myViewModel.number}" />
代码:
public class SomeModel {
public ObservableFloat number = new ObservableFloat();
}
和设置:
viewModel.number.set(3.14f);
<小时>
但是如果我对 int 到字符串尝试同样的事情,我会崩溃.
But if I try the same thing for ints to strings I get a crash.
public ObservableInt number = new ObservableInt();
与
viewModel.number.set(42);
我得到以下信息:
FATAL EXCEPTION: main
Process: ...myapplication, PID: 14311
android.content.res.Resources$NotFoundException: String resource ID #0xfa0
at android.content.res.Resources.getText(Resources.java:1123)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4816)
at ...executeBindings(ActivityAdaptersBinding.java:336)
at android.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:355)
<小时>
有什么想法吗?谢谢!
Any ideas? Thanks!
推荐答案
android:text
with an int
假定 int
是一个字符串资源 ID.使用 android:text="@{Integer.toString(myViewModel.number)}"
.
android:text
with an int
assumes that the int
is a string resource ID. Use android:text="@{Integer.toString(myViewModel.number)}"
.
您还需要导入 (不再需要)Integer
类:
You will also need to import the (no longer needed)Integer
class:
这篇关于Android 数据绑定@BindingConversion 失败,int 到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!