How to set strings.xml values at build time?

╄→гoц情女王★ 提交于 2021-02-08 07:33:25

问题


I'm building my Android application with Ant, and would like to set one of the values in my strings.xml at build time. For example, I could use

<string name="app_name">MyApp-DEBUG</string>

with a debug build, or I could use

<string name="app_name">MyApp<string>

for a release build. Is this possible?


回答1:


There are two tasks in Ant that can help:

First is the <replace>. You give it a file name that contains parameters that can be replaced, and you give the <replace> task the values for those parameters. It replaces them in the file. I don't like this task because it's used to replace stuff that is under version control, and if you're not careful, you can end up changing the file without meaning to.

settings.xml
<settings>
     <properties>
          <property name="server" value="@SERVER@"/>
     </properties>'
</settings>
Replace Task
 <replace file="settings.xml">
    <replacetoken token="@SERVER@"  value="google.com"/>
 </replace>

I've seen plenty of version control repositories where revision #3 of the replaced file was an accidental checkin of the the file with the replaced parameters (and not realizing it until the next release when the parameters didn't get changed). Then version #4 is a duplicate of version #2 which had the replacement parameters. Followed by a bad version #5, followed by a version #6 which restores the file, and on and on.

My preferred method is to copy the file over to another directory, and use <filterset>/<filter> tokens to change the file while being copied:

 <copy todir="${target.dir}"
    file="settings.xml">
    <filterset>
        <filter token="SERVER" value="google"/>
    </filterset>
  </copy>

Both can use a property file instead of specifying individual tokens. The <copy>/<filterset> pair can take a fileset of files and replace a bunch of tokens at once. (Be careful not to pass it a binary file!).




回答2:


try this code, it works for me

<target name="app-name-debug">
    <replaceregexp file="res/values/strings.xml" match='name="app_name"(.*)'
        replace='name="app_name"&gt;MyApp-DEBUG&lt;\/string&gt;'/>
</target>
<target name="app-name-release">
    <replaceregexp file="res/values/strings.xml" match='name="app_name"(.*)'
        replace='name="app_name"&gt;MyApp&lt;\/string&gt;'/>
</target>


来源:https://stackoverflow.com/questions/12084002/how-to-set-strings-xml-values-at-build-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!