8

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.

8
  • 1
    use data binding medium.com/@ubuntudroid/… Commented Apr 10, 2019 at 6:10
  • Try the below Link will help you:stackoverflow.com/questions/3656371/… Commented Apr 10, 2019 at 6:21
  • @Rahul.. i donot have data object in xml. I have already gone thru the article. Anyways Thanks for mentioning it . Commented Apr 10, 2019 at 6:27
  • 3
    You'll need to source the value for %s from somewhere, and DataBinding is the most "xml" way I can think of to achieve it. Commented Apr 10, 2019 at 6:35
  • 2
    android:text= "@{@string/generic_name(user.name)}" don't you think android:text= "@{@string/generic_name(Hello World)}" or @{String.format(@string/Hello, Hello World)} you can do this data binding Hello world is in inside back tick Commented Apr 10, 2019 at 6:37

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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)}"

1 Comment

As supportive information, it requires data binding enabled in gradle and a layout tag as a root tag in the view.xml.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.