[英]How can I convert string to int/Integer if the string contains word?
基本上我想将字符串单词转换为int,就像从xml一样,但是现在要从原始文件中转换。 我可以从xml做到这一点:
final int[] colorArray = getResources().getIntArray(R.array.colors_int);
我在xml文件中有这个:
<integer-array name="colors_int">
<item>@color/red</item>
<item>@color/yellow</item>
<item>@color/blue</item>
</integer-array>
这样,我可以轻松地在对象上设置颜色:
view.setBackgroundColor(colorArray[i]);
但是现在我有一个原始文件,其中包含用空格将它们分开的颜色名称:“蓝红色黄”
如何将它们读入int数组/ Integer arraylist,以便可以轻松为对象着色? 我尝试了这个:
input_file_int.add( Integer.parseInt(line));
但是它没有用,因为字符串不是int。
java.lang.NumberFormatException: Invalid int: "blue"
使用字符串arraylist,它可以完美工作,但是我不能使用字符串为对象着色。
我该怎么办?
编辑:
我有这个示例原始文件:
black
gray
silver
maroon
red
olive
我的colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<!--16 basic color -->
<color name="black">#000000</color>
<color name="gray">#808080</color>
<color name="silver">#C0C0C0</color>
<color name="white">#FFFFFF</color>
<color name="maroon">#800000</color>
</resources>
那就是我初始化Integer ArrayList的方式:
ArrayList<Integer> input_file_int= new ArrayList<Integer>();
您可以创建颜色的Map
:
Map<String, Integer> colors = new HashMap<String, Integer>();
colors.put("blue", 0xff00ff00);
input_file_int.add(colors.get("blue"));
编辑:如果您要对xml上列出的颜色进行查找,则可以这样做:
Resources resources = getResources();
int colorId = resources.getIdentifier(line, "color", "com.mypackage.myapplication");
int color = resources.getColor(colorId);
input_file_int.add(color);
// Your arraylist
ArrayList<Integer> input_file_int = new ArrayList<Integer>();
// Read raw file
Scanner scanner = new Scanner(getResources().openRawResource(
R.raw.colors));
try {
while (scanner.hasNext()) {
switch (scanner.next()) {
// include case of your all 16 (or any number of) colors of your
// colors.xml file
case "black":
input_file_int.add(Integer.parseInt(getResources()
.getString(R.color.black).substring(3), 16));
break;
case "gray":
input_file_int.add(Integer.parseInt(getResources()
.getString(R.color.gray).substring(3), 16));
break;
case "silver":
input_file_int.add(Integer.parseInt(getResources()
.getString(R.color.silver).substring(3), 16));
break;
// and keep going on
default:
break;
}
}
} catch (Exception e) {
Log.e(getTitle().toString(), e.getMessage());
} finally {
scanner.close();
}
// Now, Arraylist contains true Integer value of colors
// Be aware you can't directly use it.
// Use it like this...
view.setBackgroundColor(0xff000000 + input_file_int.get(2));
// Silver in this case
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.