SimpleCoder
SimpleCoder

Reputation: 1715

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.

Upvotes: 8

Views: 7807

Answers (3)

Christopher Pickslay
Christopher Pickslay

Reputation: 17782

There are at least 2 ways to do string formatting in a layout expression:

android:text="@{String.format(@string/str_1, viewModel.username)}"

or

android:text="@{@string/str_1(viewModel.username)}"

Upvotes: 2

Deepak J
Deepak J

Reputation: 234

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.

Upvotes: 7

Adib Faramarzi
Adib Faramarzi

Reputation: 4060

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.

Upvotes: 3

Related Questions