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

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

提交回复
热议问题