Android Data Binder bug: androidbinder
Following the official tutorial to learn how to use data binding, the function is indeed very powerful. This is a huge step for Android to become MVVM and a small step for Native development to move closer to the Web.
One of the binding methods is to directly use resource data, for example:
android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}"
Official Tutorial:
The layout file of the full version is as follows:
<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data class="ResourceBinding"> <variable name="large" type="boolean" /> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:padding="@{large? @dimen/largePadding : @dimen/smallPadding}" android:background="@android:color/black" android:textColor="@android:color/white" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </LinearLayout></layout>
largePadding
AndsmallPadding
All are defined indimens.xml
File.
<dimen name="largePadding">20dp</dimen><dimen name="smallPadding">5dp</dimen>
Bind the large variable in the Java code and assign the valueture
.
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ResourceBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_resource); binding.setLarge(true);}
Theoretically, this should be fine, but an error occurs during the Run project. The error message is as follows:
cannot find the setter for attribute 'android:padding' on android.widget.TextView with parameter type float.
It seems like DataBinder@dimen/largePadding
Resolvedfloat
Type, you can try type conversion:
android:padding="@{large? (int)@dimen/largePadding : (int)@dimen/smallPadding}"
After compilation is passed, the running result is correct. It should be a bug in DataBinder. The original resource binding has such advanced usage, and type conversion can be performed directly-(int)@dimen/largePadding
.
It feels amazing. You must read the source code to understand how DataBinder works.