Organizing Strings.xml

南笙酒味 提交于 2019-11-27 14:29:39

问题


I'm making an android app and since I've just started I want to try get the most organised code/resources. In my strings.xml file so far I have this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">GameController</string>
<string name="stop">Stop</string>
<string name="start">Start</string>
<string name="preferences">Preferences</string>
<string name="back">Back</string>
</resources>

All of the strings except app_name are used in an options menu. But since I will be adding much more strings I was thinking that it might be better to do something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">GameController</string>
<string name="menu_stop">Stop</string>
<string name="menu_start">Start</string>
<string name="menu_preferences">Preferences</string>
<string name="menu_back">Back</string>
</resources>

Is it the best way or should I use another system?


回答1:


It depends on where the strings will be used. If "stop" will never be used anywhere but in a menu, calling it "menu_stop" is a good idea. If it'll be used all over the place then it should just be called "stop".

Also, XML comments are very useful for organizing resources.

<resources>
    <string name="app_name">GameController</string>

    <!-- Menu Strings -->
    <string name="menu_stop">Stop</string>
    <string name="menu_start">Start</string>
    <string name="menu_preferences">Preferences</string>
    <string name="menu_back">Back</string>
</resources>

Finally, if you find you have tons and tons of string resources you may want to go so far as to separate them into different xml files: menu_strings.xml, dialog_strings.xml, etc.

menu_strings.xml

<resources>
    <!-- Menu Strings -->
    <string name="menu_stop">Stop</string>
    <string name="menu_start">Start</string>
    <string name="menu_preferences">Preferences</string>
    <string name="menu_back">Back</string>
</resources>

dialog_strings.xml

<resources>
    <string name="dialog_cancel_yes">Yes, cancel.</string>
    <string name="dialog_cancel_no">No, do not cancel.</string>
</resources>



回答2:


This is kind of a subjective question, really. You should use whatever you find easier to handle. I certainly do the second type of naming when I'm using layouts and drawables (e.g. button_x, ninepatch_x, icon_x, etc.), just because it keeps them next to each other, and is easier to narrow down quickly with Content Assist. In XML, you can use comments to group them together, and add white space, just anything that makes it easier for you to find what you need, and quickly.



来源:https://stackoverflow.com/questions/4597216/organizing-strings-xml

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