Search code examples
androidstringandroid-layoutandroid-xmlandroid-xml-attribute

Use Strings with placeholder in XML layout android


I have a string with placeholder e.g

<string name="str_1">Hello %s</string>

I want to use this in xml layout as android:text="@string/str_1". Is there any way to use this in xml layout to fill the placeholder? Thanks in advance. I already know String.format(str,str...) in java/kotlin but i want to use this in xml layout without data binding.


Solution

  • You can use something like this. Write your string in your (strings.xml) with declaring a string variable (%1$s) inside it. For decimal, we use (%2$d).

    <string name="my_string">My string name is %1$s</string>
    

    And inside the android code (yourFile.java), use this string where you want it.

    String.format(getResources().getString(R.string.my_string), stringName);
    

    This is not a good answer but it may help you get some idea to get going.

    Thanks.