Cannot find method safeUnbox(java.lang.Boolean) in class android.databinding.ViewDataBinding
我是Android数据绑定库的新手。
我有很多警告,例如:
1 | warning: viewModel.someBoolean.getValue() is a boxed field but needs to be un-boxed to execute android:checked. This may cause NPE so Data Binding will safely unbox it. You can change the expression and explicitly wrap viewModel.someBoolean.getValue() with safeUnbox() to prevent the warning |
它的定义如下:
在ViewModel中
1 | val someBoolean: MutableLiveData<Boolean> = MutableLiveData() |
布局中
1 2 3 4 5 6 | <RadioButton android:id="@+id/someBooleanRadioButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:checked="@={viewModel.someBoolean}" android:text="@string/boolean_description" /> |
我试图通过添加safeUnbox()来修复它:
1 2 3 4 5 6 | <RadioButton android:id="@+id/someBooleanRadioButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:checked="@={safeUnbox(viewModel.someBoolean)}" android:text="@string/boolean_description" /> |
但是我得到编译错误:
1 | msg:cannot find method safeUnbox(java.lang.Boolean) in class android.databinding.ViewDataBinding |
在已经定义的gradle中
1 2 3 | dataBinding { enabled = true } |
和
有什么想法如何解决?
Android Studio 3.1.4
摇篮4.4
科特林1.2.61
附言 只是重复的问题。 所有问题都与如何解决警告有关,但我的问题是在添加
我说的是布尔值,对于整数,双精度,字符等,此解决方案相同。
当您具有双向绑定时,则不能使用
1 2 3 4 5 6 7 8 9 | <variable name="enabled" type="Boolean"/> .... <Switch android:checked="@={enabled}" /> |
解决方案1
将
1 2 3 | <variable name="enabled" type="boolean"/> |
解决方案2
一个很长的路要走,就是为safeBox和safeUnbox方法创建方法。 看这里。
什么是safeUnbox()方法?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public static int safeUnbox(java.lang.Integer boxed) { return boxed == null ? 0 : (int)boxed; } public static long safeUnbox(java.lang.Long boxed) { return boxed == null ? 0L : (long)boxed; } public static short safeUnbox(java.lang.Short boxed) { return boxed == null ? 0 : (short)boxed; } public static byte safeUnbox(java.lang.Byte boxed) { return boxed == null ? 0 : (byte)boxed; } public static char safeUnbox(java.lang.Character boxed) { return boxed == null ? '\\u0000' : (char)boxed; } public static double safeUnbox(java.lang.Double boxed) { return boxed == null ? 0.0 : (double)boxed; } public static float safeUnbox(java.lang.Float boxed) { return boxed == null ? 0f : (float)boxed; } public static boolean safeUnbox(java.lang.Boolean boxed) { return boxed == null ? false : (boolean)boxed; } |