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

前端 未结 4 2035
误落风尘
误落风尘 2021-01-04 20:03

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

相关标签:
4条回答
  • 2021-01-04 20:50

    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>
    
    0 讨论(0)
  • 2021-01-04 20:51

    It's indeed possible.

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE resources [
      <!ENTITY appname "MyAppName">
      <!ENTITY author "MrGreen">
    ]>
    
    <resources>
        <string name="app_name">&appname;</string>
        <string name="description">The &appname; app was created by &author;</string>
    </resources>
    

    You can even define your entity globaly e.g:

    res/raw/entities.ent:

      <!ENTITY appname "MyAppName">
      <!ENTITY author "MrGreen">
    

    res/values/string.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE resources [
        <!ENTITY % ents SYSTEM "./res/raw/entities.ent">
        %ents;   
    ]>
    
    <resources>
        <string name="app_name">&appname;</string>
        <string name="description">The &appname; app was created by &author;</string>
    </resources>
    
    0 讨论(0)
  • 2021-01-04 20:58

    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));
    
    0 讨论(0)
  • 2021-01-04 21:06

    Well, I don't think this is possible. Because once the resources are allocated android won't allow us to change them dynamically in the air. Instead you can try having your Strings in a separate class and change them as you run through your code.

    0 讨论(0)
提交回复
热议问题