[英]How do I access getStringArray with a variable
I'm sure there's a perfect fine way to do this much better, but basically what I want is to create 2-dim array via strings.xml.我确信有一个完美的好方法可以做得更好,但基本上我想要的是通过 strings.xml 创建 2-dim 数组。
ie. IE。 I have a main category:我有一个主要类别:
<string-array name="main_categories">
<item>index_etf</item>
<item>region_etf</item>
<item>commodity_etf</item>
</string-array>
and a bunch of subcategories:和一堆子类别:
<string-array name="index_etf">
<item>DOW</item>
<item>NASDAQ</item>
</string-array>
instead of doing it hardcoded like:而不是像这样硬编码:
MainCategoryArray = getResources().getStringArray(R.array.main_categories);
IndexETFArray = getResources().getStringArray(R.array.index_etf);
...
I'd like to do something like:我想做类似的事情:
MainCategoryArray = getResources().getStringArray(R.array.main_categories);
loop through the main array and populate the sub categories
Not sure if I can access the getStringArray
with an int
variable based on the content of the MainCategoryArray, is there?不确定我是否可以根据 MainCategoryArray 的内容使用int
变量访问getStringArray
,对吗?
Any better approach to build a multi-dimensional based on strings.xml?有没有更好的方法来构建基于strings.xml 的多维? Sorry, new to this.对不起,新来的。
Try this,尝试这个,
Variable declaration变量声明
private final static String TAG = MainActivity.class.getSimpleName();
private ArrayList<String> mainCategoryArray;
private ArrayList<ArrayList<String>> categoryArrays = new ArrayList<>();
Usage用法
mainCategoryArray = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.main_categories)));
for(String mainCategory : mainCategoryArray){
try {
categoryArrays.add(new ArrayList<>(Arrays.asList(getResources().getStringArray(getResources().getIdentifier(mainCategory, "array", getPackageName())))));
} catch (Resources.NotFoundException e){
Log.e(TAG, e.toString());
}
}
Sample strings.xml array示例 strings.xml 数组
<string-array name="main_categories">
<item>index_etf</item>
<item>region_etf</item>
<item>commodity_etf</item>
</string-array>
<string-array name="index_etf">
<item>DOW</item>
<item>NASDAQ</item>
</string-array>
<string-array name="region_etf">
<item>DOW</item>
<item>NASDAQ</item>
</string-array>
<string-array name="commodity_etf">
<item>DOW</item>
<item>NASDAQ</item>
</string-array>
Hope this helps :)希望这可以帮助 :)
You can use qualifiers on resources so android itself choose appropriate resources based on the qualifiers.您可以在资源上使用限定符,以便 android 本身根据限定符选择合适的资源。 For example you can have values-small
for small screens and values-large
for large screen and values
for other screen sizes.例如,您可以为小屏幕设置values-small
,为大屏幕设置values-large
,为其他屏幕尺寸设置values
。 You can see all available qualifiers here .您可以在此处查看所有可用的限定符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.