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

前端 未结 9 922
爱一瞬间的悲伤
爱一瞬间的悲伤 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:15

    2019 Update, Android studio to 3.4, Android Gradle Plugin to 3.4

    No more required to import

    <import type="java.lang.String" />" 
    

    for string operations. Please check this answer.

    0 讨论(0)
  • 2020-12-07 14:20

    In case you can't change the resource string to contain %s at the end (eg. because it's used elsewhere without the suffix):

    android:text="@{@string/Generic_Text.concat(Profile.name)}"
    

    If Profile.name can't be null, that's enough. However, if a null happens, it'll crash. You have to add another layer:

    android:text="@{@string/Generic_Text.concat(Objects.toString(Profile.name))}"
    

    (which requires <import type="java.util.Objects"/> to work.)

    Again: all this extra work is worth it only if you have the resource string used elsewhere. The second reason is when you want to handle null as "empty string" instead of a "null" literal.

    0 讨论(0)
  • 2020-12-07 14:20

    Just using + operator works for me:

    android:text= "@{@string/Generic_Text +' '+ Profile.name)}"
    

    String.xml will be:

    <string name="Generic_Text">Hello</string>
    
    0 讨论(0)
提交回复
热议问题