简体   繁体   English

Android Studio如何将具有ID的字符串转换为Int?

[英]android studio how to convert string with id to int?

Is there any way to convert string with id (for example: String id = "R.id.id" ) to int? 有什么方法可以将具有id的字符串(例如: String id = "R.id.id" )转换为int吗?

I have tried this: 我已经试过了:

String st = "R.id.id";
int id = Integer.parseInt(st);

But it didn't work. 但这没有用。

Thanks for help! 感谢帮助!

What you are asking is completely wrong. 您要问的是完全错误的。

"R.id.id" is a String that can't be converted in a int. "R.id.id"无法在int中转换String

It will always throw a NumberFormatException . 它将始终抛出NumberFormatException

Check the javadoc : 检查javadoc

Parses the string argument as a signed decimal integer. 将字符串参数解析为带符号的十进制整数。 The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\-') to indicate a negative value or an ASCII plus sign '+' ('\+') to indicate a positive value. 字符串中的字符都必须全部为十进制数字,但第一个字符可以是表示负值的ASCII减号'-'('\\ u002D'),也可以是ASCII加号'+'('\\ u002B')表示正值。 The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method. 返回结果整数值,就好像参数和基数10作为parseInt(java.lang.String,int)方法的参数一样。

If the resource used in your strings.xml with the same id is a integer, you have to use somenthing different: 如果您的strings.xml使用的具有相同id的资源是整数,则必须使用其他方式:

<resources>
    <string name="mystring">12</string>
</resources>

Use this code to retrieve a string: 使用以下代码检索字符串:

String string = getString(R.string.mystring);

try{
   int number = Integer.parseInt(string);
} catch (NumberFormatException nfe){
  //.....
}

String that consists of other than numeric values can not be converted to int or into any of the numeric data types. 包含非数字值的String不能转换为int或任何数字数据类型。 However if a string hold numeric value then you can convert it into int or other numeric data types. 但是,如果字符串包含数字值,则可以将其转换为int或其他数字数据类型。 And the reason for it is every programming language has its syntax defined, if you want to assign value through character You can do as 原因是每种programming language都定义了其syntax ,如果您想通过字符分配值,您可以

int variableName = 'a';
or
int variableName = 'b';

etc. this is spacial numeric assigning in java 'a' equals 97 & 'b' equals 98 . 等等。这是在Java中分配的数字'a'等于97'b'等于98

Or if a string hold numeric value you can convert it as 或者,如果字符串包含数字值,则可以将其转换为

<resources>
    <string name="stringVal">500</string>
</resources>

get like this 像这样

String string = getString(R.string.stringVal);


   int anyName= Integer.parseInt(string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM