我希望根据条件将TextView的文本设置为其中之一。
Android数据绑定文档建议如果文本是视图模型的属性,则可以有条件地设置文本。例如:
android:text="@{user.displayName != null ? user.displayName : user.lastName}"
但是有没有办法从strings.xml中设置文本而不是在我的视图模型中添加它呢?我想要像这样的东西-
android:text="@{viewModel.expanded ? @string/collapse : @string/expand}"
XML看起来有点像这样:
<?xml version="1.0" encoding="UTF-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto">
<data class="TravellerInfoBinding">
<import type="android.view.View" />
<variable name="viewModel" type="com.myproject.viewmodel.TravellerInfoViewModel" />
</data>
<LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@drawable/expandable_arrow_blue" />
<TextView style="@style/primary_pair_element_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.expanded ? @string/taxes_fees_detail : @string/hide_taxes_fees_detail}"
android:textSize="12sp" />
</LinearLayout>
</layout>
这是我的视图模型 -
package com.myproject.viewmodel;
imports...
public class TravellerInfoViewModel extends BaseObservable {
@Bindable
private final TaxDetailsViewModel taxDetailsViewModel;
@Bindable
private boolean expanded;
Constructor....
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
notifyPropertyChanged(BR.expanded);
}
public void toggleExpanded() {
setExpanded(!expanded);
}
}
Error: Identifiers must have user defined types from the XML file. viewModel is missing it
。 - Rajkiran