2016-10-14 9 views
10

Im sử dụng DataBinding Api để đặt chế độ xem trong bố cục Android. Đây là cách bố trí của tôi.Tôi muốn concat hai chuỗi cho một TextView trong android, Binding dữ liệu Api

Layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<layout xmlns:android="http://schemas.android.com/apk/res/android"> 
    <data> 
    <variable name="user" type="testing.sampleapp.com.sampleapp.User"/> 
    </data> 
<LinearLayout 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <TextView android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@{ "Hello " + user.firstName}"/> 
</LinearLayout> 

Tôi muốn các TextView để hiển thị Xin chào UserName. Làm thế nào để đạt được điều này bằng cách sử dụng api ràng buộc dữ liệu.

Trả lời

33

concate nó với mộ giọng (`)

android:text="@{`Hello ` + user.firstName}"/> 
+0

Đúng vậy. Cảm ơn . Tôi đã sử dụng dấu phẩy ngược đơn ('). Grave accent (') làm việc cho tôi. –

+0

@SasankSunkavalli rất vui được giúp bạn :), luôn sử dụng dấu trọng âm cho chuỗi khi sử dụng DataBinding. –

3

Khai báo chuỗi của bạn trong strings.xml

như "Hello %$1s , (whatever you want to add then add here)".

sử dụng amd String.format(stringResource, upsatename);

+0

Tôi biết điều này sẽ hiệu quả, Nhưng tôi muốn sử dụng cách concat –

+0

bạn có thể kết hợp nhiều ở đây bằng% $ 1s,% $ 2s ... –

+9

Bạn cũng có thể sử dụng tài nguyên chuỗi đã định dạng trong biểu thức: 'android: text =" @ {@ string/hello (user.firstName)} "' –

2

Kể từ xml hỗ trợ dấu nháy đơn cho các giá trị của thuộc tính, bạn cũng có thể làm điều này:

android:text='@{"Hello "+user.firstName}' 
0

Để làm một concat trong cách bố trí xml:

<data> 

/*This is used for android view*/ 
<import type="android.view.View" /> 

/*This is used for android resources*/ 
<import type="com.myapp.R" /> 

/*This is app context*/ 
<variable 
    name="context" 
    type="android.content.Context" /> 

/*This is used for model data*/ 
<variable 
    name="item" 
    type="com.myapp.models.Chapter" /> 
</data> 

android:text="@{item.serialNo.concat(@string/space).concat(item.title)}" 

Trong strings.xml Tôi đã thêm mã cho khoảng trắng:

<string name="space">\u0020</string> 
Các vấn đề liên quan