一.遇到类型转换的问题,以前总是模糊不清,看了源码之后才豁然开朗。
就一int转String为例:据我了解,一般有三种方法。也就是自己(int)、对象(String)和强转。其他的转变基本一样。
1.通过自己转变
String a = Integer.toString(i);
2.对象来转变
String b = String.valueOf(i);
这是String中valueOf方法的源码:
它的类型转换调用的是int类型的方法。换汤不换药。
/**
* Returns the string representation of the <code>int</code> argument.
* <p>
* The representation is exactly the one returned by the
* <code>Integer.toString</code> method of one argument.
*
* @param i an <code>int</code>.
* @return a string representation of the <code>int</code> argument.
* @see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i);
}
3.强转(比较难理解)
String c = i + "";
i先升级为String类型,再与""字符串合并。
二.再有一个就是由于类型转变包的错了:
错误:android.content.res.Resources$NotFoundException: String resource ID #0x1
原因:一般发生在参数 int resId 错误,你把String赋值给int的resId,所以编译器找不到正确的resource于是报错。
最简单的例子,检查一下你的Toast.makeText()啊textView.setText啊之类的函数,这种函数通常有几个重载,如:
textView.setText(CharSequence text);
textView.setText(int resId);
……
如果不小心将一个int值传给了它,那它不会显示该int值,而是跑到工程下去找一个对应的resource的id,当然是找不到的,于是就报错啦。
解决办法:
如果要显示该int值,就要将int转化成String或者CharSequence,也就是以上的方法。
个人比较喜欢这么干:在该int值后面+”“,强制转为String。简单易用。