2016-06-09 26 views
5

我想將TextView的文本有條件地設置爲一個或另一個。Android - 使用數據綁定的條件文本值

Android Data Binding文檔建議您可以有條件地設置文本,如果文本是視圖模型的屬性。例如

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); 
    } 

} 
+0

我以爲語法工作。你遇到什麼問題? – CommonsWare

+0

這是正確的,你有什麼錯誤嗎? –

+0

@CommonsWare獲取此編譯錯誤'錯誤:標識符必須具有XML文件中的用戶定義類型。 viewModel缺少它' – Rajkiran

回答

0

這裏有一個固定/變通辦法:

  1. 定義佈局的重複Xml定義要針對每個塊一個條件值
  2. ,設定的條件中的一個值
  3. 設置每個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" 
     />