I want to concat two strings for a TextView in android, Data Binding Api

前端 未结 10 831
太阳男子
太阳男子 2020-12-23 14:04

Im using DataBinding Api for setting the views in android layouts. Here is my layout.

layout.xml



        
10条回答
  •  别那么骄傲
    2020-12-23 14:50

    Many ways to concat strings

    1. Using string resource (Most preferable because of localization)

    android:text= "@{@string/generic_name(user.name)}"

    Just make string resource like this.

    Hello %s
    

    2. Hard coded concat

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

    3. Using String's concat method

    android:text="@{user.firstName.concat(@string/space).concat(user.lastName)}"
    

    Here space is an html entity which is placed inside strings.xml. Because XML does not accept Html entities or special characters directly. (Link Html Entities)

    \u0020
    

    4. Using String.format()

    android:text= "@{String.format(@string/hello, user.name)}"
    

    you have to import String class in layout in this type.

    
    
        
            
        
        
        
    
    

    5. Another method

    android:text="@{@string/generic_name(user.firstName,user.lastName)}"
    

    In this case put a string resource in strings.xml

    %1$s, %2$s
    

    There can be many other ways, choose one you need.

提交回复
热议问题