我想有条不紊地将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);
- }
- }
解决方法
这是一个修复/解决方法:
>定义您想要条件值的布局的重复Xml定义
>对于每个块,设置其中一个条件值
>根据数据绑定布尔值设置每个Xml定义的可见性
不是理想的解决方案,不是很漂亮..但功能相当 – 并且在临时工作直到找到正确的解决方案.
这是我为android:textStyle解决它的方法,我有一个特殊的情况要求以粗体显示值.
- <variable
- name="viewmodel"
- type="com.demo.app.Someviewmodel"/>
- ...
- <TextView
- style="@style/RowValue"
- android:visibility="@{ ! viewmodel.boldRow ? View.VISIBLE : View.GONE}"
- android:text="@{viewmodel.currentValue}"
- />
- <TextView
- style="@style/RowValue"
- android:visibility="@{ viewmodel.boldRow ? View.VISIBLE : View.GONE}"
- android:text="@{viewmodel.currentValue}"
- android:textStyle="bold"
- />