Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 585
SimpleCoder Avatar asked Mar 04 '23 04:03

SimpleCoder


2 Answers

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.

like image 140
Deepak J Avatar answered Mar 15 '23 04:03

Deepak J


It's not possible to format your strings directly in your XML. Inside your code you can use both String.format and context.getString() to get and format your string.

If you want to show something just in the XML and not have it in the final build (only have it in compile time), you can also use tools: namespace like following:

<TextView 
...

    tools:text="Hello, this is a test"

/>

This will only appear in the layout editor and will not have any effect in the APK. It can also be used for other fields too, like tools:visiblity.

like image 36
Adib Faramarzi Avatar answered Mar 15 '23 05:03

Adib Faramarzi