1

I am trying to concatenate string and integer in string.xml like below...

<integer name="min_length">10</integer>
<string name="error">Enter minimum @integer/min_length chars</string>

So that the value of getString(R.string.error) could be "Enter minimum 10 chars". But getting error, please help!

4
  • I don't think its possible. Commented Jan 11, 2016 at 13:47
  • 2
    it is not possible. Do it a Runtime (here an example) Commented Jan 11, 2016 at 13:47
  • I know the solution via run time. But I need the way what I mentioned. Thanks. Commented Jan 11, 2016 at 13:57
  • Can strings.xml even contain <integer> tags? Commented Jan 11, 2016 at 17:10

4 Answers 4

6

From the link Shree posted

XML

<string name="error">Enter minimum %1$d chars</string>

Java

int min_length = 10;
Resources res = getResources();
String text = String.format(res.getString(R.string.error), min_length);
Sign up to request clarification or add additional context in comments.

Comments

1

You can not concatenate strings or integer and strings in xml. You can do refer to another string or integer in one string or integer tag respectively in xml , but only one. Like:

 <integer name="min_length">10</integer>

<integer name="min">@integer/min_length</integer>

You can refer integer inside integer and string inside string .

If you try to do what you mentioned above android studio , you will be thrown away with error.

Comments

1

A quick solution for your question!

Write your Integer and String like

<integer name="min_length">10</integer>
<string name="error">Enter minimum min_length chars</string>

And Concat them like

String string = 
getString(R.string.error).replace("min_length",
 String.valueOf(getResources().getInteger(R.integer.min_length)))

In Android you can't concatenate Strings inside xml without any logical codes like you have shown

See more at formatting and styling String resources

Comments

1

You can do this now using DataBinding.

<TextView android:text='@{"Enter minimum " + @string/min_length)}' />

Read more about DataBinding here

Comments

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.