Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do string substitution in Android resource XML files directly?

In my android app, I have a large string resource xml file. I want to make reference and reuse declared resources values within String values. Is it possible to have the R class resolve referenced values (a la @string/db_table_name)?

<resources>
<string name="db_table_name">tbl_name</string>
<string name="ddl">create table @string/tbl_name</string>
</resources>

Is there a way of doing this. In regular Java world, some tools use ${varname} expression to resolve reference. Can this be done at all in Android?

like image 292
vladimir.vivien Avatar asked Jul 13 '11 13:07

vladimir.vivien


2 Answers

Add a %s to your second resource string (the one that you want to be dynamic) where you want it to be modified. i.e.,

<resources>
<string name="db_table_name">tbl_name</string>
<string name="ddl">create table %s</string>
</resources>

and in your code use getString() to work the magic,

getString(R.string.ddl, getString(R.string.db_table_name));
like image 59
source.rar Avatar answered Nov 12 '22 17:11

source.rar


Yes, it is possible without writing any Java/Kotlin code, only XML, by using this small library I created which does so at buildtime: https://github.com/LikeTheSalad/android-string-reference

Usage

Based on your example, you'd have to set your strings like this:

<resources>
  <string name="db_table_name">tbl_name</string>
  <string name="template_ddl">create table ${db_table_name}</string>
</resources>

And then, after building your project, you'll get:

<resources>
  <string name="ddl">create table tbl_name</string>
</resources>
like image 37
César Muñoz Avatar answered Nov 12 '22 18:11

César Muñoz