How do I use databinding to combine a string from resources with a dynamic variable in XML?

前端 未结 9 927
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 13:30

I have a TextView which has a hardcoded string and I have a dynamic variable that I want to put at the end of this string. This is my code:



        
9条回答
  •  一生所求
    2020-12-07 14:11

    Many ways to concat strings

    1. Using string resource (Recommended because 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}"/>
    

    This is useful when you need hardcoded append like + for phone number.

    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. concat two strings by string resource.

    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.

提交回复
热议问题