2017-02-27 24 views
3

使用數據綁定來連接兩個動態字符串是可能的嗎?Concat使用數據綁定的兩個動態字符串

我的代碼看起來像:

<TextView 
        android:id="@+id/text_view_activity_profile_name" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_below="@id/image_view_activity_profile_small_photo" 
        android:layout_centerHorizontal="true" 
        android:layout_marginTop="15dp" 
        android:text="@={userdata.firstName+' '+userdata.lastName}" 
        android:textColor="@color/white" 
        android:textSize="24sp" /> 

,但它是不正確的方式: 錯誤:(52,42)中的表達(firstNameUserdataCha)+(lastNameUserdata)不能不能倒置:雙向綁定運算符+僅支持單個動態表達式。

+0

用setText在你的java代碼中設置你的textview。 –

回答

7

嘗試像這樣反而

android:text='@{userdata.firstName+" "+userdata.lastName}' 

或交替...

android:text='@{String.format("%s %s", userdata.firstName, userdata.lastName)}' 
+5

這是對的。不能使用雙向數據綁定('@ = {...}'而不是'@ {...}')和字符串連接。第三個(也是更好的)選項是使用資源格式來支持多種語言:'android:text =「@ {@ string/name(userdata.firstName,userdata.lastName)}」' –

+0

謝謝!這是正確的解決方案 –

2

它不能編譯,因爲你使用的雙向數據綁定。由於使用了兩個變量,Android DataBinding生成的類將無法將TextView的值指定回userData。您可以使用單向數據,而不是綁定:

android:text='@{userData.firstName + " " + userData.lastName}'

如果你真的想使用雙向數據綁定,然後進行自定義轉換爲。