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:
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.
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.
Just using +
operator works for me:
android:text= "@{@string/Generic_Text +' '+ Profile.name)}"
String.xml will be:
<string name="Generic_Text">Hello</string>