升级Gradle至3.5.1后,布局中MutableLiveData致Data Binding失效
Looks like you hit a bug in the Data Binding compiler included with Gradle 3.5.1. The issue stems from how it handles untyped MutableLiveData variables in your layout XML—instead of generating valid Java code, it outputs an illegal expression with a wildcard ? that breaks compilation.
Root Cause
When you declare a variable as type="MutableLiveData" (without specifying a generic type), Gradle 3.5.1's Data Binding compiler incorrectly tries to generate code using ? as the type for the selectionGetValue variable:
? selectionGetValue = null; // Illegal start of expression
In contrast, Gradle 3.5.0 correctly infers the type as java.lang.Object for untyped MutableLiveData instances, producing valid code.
Solution: Specify a Generic Type for MutableLiveData
The simplest fix is to explicitly define the generic type for your selection variable in the layout XML. Since your spinner uses android:selectedItem="@={selection}" (two-way binding), you should match the type to whatever your spinner items are. For example, if your items are Object instances (as your collection variable suggests), update the variable declaration:
<variable name="selection" type="MutableLiveData<Object>" />
(Note: In XML, you need to escape < as < to avoid parsing errors.)
If your spinner uses a specific type (e.g., String, a custom model class), replace Object with that type instead—this will also make your code more type-safe.
Verification Steps
- Update the
selectionvariable in your layout XML with the explicit generic type. - Clean your project: Go to
Build > Clean Projectin Android Studio. - Rebuild your project: Go to
Build > Rebuild Project.
This should resolve the compilation error, as the Data Binding compiler will now generate valid code for the selectionGetValue variable using your specified generic type.
Temporary Workaround (If You Can't Specify a Generic Type)
If for some reason you need to keep an untyped MutableLiveData, you could wrap it in a custom class or use LiveData instead (though this won't work for two-way binding). However, specifying the generic type is the recommended and most robust fix.
内容的提问来源于stack exchange,提问作者Akbolat SSS

