Android – 使用数据绑定的条件文本值

前端之家收集整理的这篇文章主要介绍了Android – 使用数据绑定的条件文本值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想有条不紊地将TextView的文本设置为其中一个或另一个.

Android数据绑定文档建议您可以在文本是视图模型的属性时有条件地设置文本.例如

  1. android:text="@{user.displayName != null ? user.displayName : user.lastName}"

但有没有办法从strings.xml中设置文本而不是在我的视图模型中添加它?我想要这样的东西 –

  1. android:text="@{viewmodel.expanded ? @string/collapse : @string/expand}"

XML看起来有点像这样:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto">
  3. <data class="TravellerInfoBinding">
  4. <import type="android.view.View" />
  5. <variable name="viewmodel" type="com.myproject.viewmodel.TravellerInfoviewmodel" />
  6.  
  7. </data>
  8. <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal">
  9. <ImageView android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:layout_gravity="center_vertical"
  12. android:src="@drawable/expandable_arrow_blue" />
  13.  
  14. <TextView style="@style/primary_pair_element_value"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="@{viewmodel.expanded ? @string/taxes_fees_detail : @string/hide_taxes_fees_detail}"
  18. android:textSize="12sp" />
  19.  
  20. </LinearLayout>
  21. </layout>

这是我的视图模型 –

  1. package com.myproject.viewmodel;
  2.  
  3. imports...
  4.  
  5. public class TravellerInfoviewmodel extends BaSEObservable {
  6.  
  7. @Bindable
  8. private final TaxDetailsviewmodel taxDetailsviewmodel;
  9.  
  10. @Bindable
  11. private boolean expanded;
  12.  
  13. Constructor....
  14.  
  15. public boolean isExpanded() {
  16. return expanded;
  17. }
  18.  
  19. public void setExpanded(boolean expanded) {
  20. this.expanded = expanded;
  21. notifyPropertyChanged(BR.expanded);
  22. }
  23.  
  24. public void toggleExpanded() {
  25. setExpanded(!expanded);
  26. }
  27.  
  28. }

解决方法

这是一个修复/解决方法

>定义您想要条件值的布局的重复Xml定义
>对于每个块,设置其中一个条件值
>根据数据绑定布尔值设置每个Xml定义的可见性

不是理想的解决方案,不是很漂亮..但功能相当 – 并且在临时工作直到找到正确的解决方案.

这是我为android:textStyle解决它的方法,我有一个特殊的情况要求以粗体显示值.

  1. <variable
  2. name="viewmodel"
  3. type="com.demo.app.Someviewmodel"/>
  4.  
  5. ...
  6.  
  7. <TextView
  8. style="@style/RowValue"
  9. android:visibility="@{ ! viewmodel.boldRow ? View.VISIBLE : View.GONE}"
  10. android:text="@{viewmodel.currentValue}"
  11. />
  12.  
  13. <TextView
  14. style="@style/RowValue"
  15. android:visibility="@{ viewmodel.boldRow ? View.VISIBLE : View.GONE}"
  16. android:text="@{viewmodel.currentValue}"
  17. android:textStyle="bold"
  18. />

猜你在找的Android相关文章