【发布时间】:2011-06-18 00:19:19
【问题描述】:
我有一个 int 变量,当我将此变量设置为 Android TextView 的文本时,它会抛出一个错误,可能是因为它是一个 Int。我已经检查但找不到 int 的 toString 函数。那我该怎么做呢?
int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate); //gives error
【问题讨论】:
我有一个 int 变量,当我将此变量设置为 Android TextView 的文本时,它会抛出一个错误,可能是因为它是一个 Int。我已经检查但找不到 int 的 toString 函数。那我该怎么做呢?
int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate); //gives error
【问题讨论】:
使用Integer类的静态toString()方法。
int sdRate=5;
text_Rate.setText(Integer.toString(sdRate));
【讨论】:
你有两个选择:
1) 使用String.valueOf() 方法:
int sdRate=5;
text_Rate.setText(String.valueOf(sdRate)); //faster!, recommended! :)
2) 添加一个空字符串:
int sdRate=5;
text_Rate.setText("" + sdRate));
铸造不是一个选项,会抛出一个ClassCastException
int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!
【讨论】:
你可以使用
text_Rate.setText(""+sdRate);
【讨论】:
你试过了吗:
text_Rate.setText(String.valueOf(sdRate));
【讨论】:
int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(String.valueOf(sdRate)); //no more errors
【讨论】:
String.valueOf和Integer.toString有什么区别?
toString()?
也许你应该这样尝试
int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate+""); //gives error
【讨论】: