【发布时间】:2018-12-22 06:07:03
【问题描述】:
代码 1:
public void displayQuantity(int number) {
TextView quantityTV = (TextView) findViewById(R.id.quantity_tv);
quantityTV.setText( " "+ number);
}
代码 2:
public void displayQuantity(int number) {
TextView quantityTV = (TextView) findViewById(R.id.quantity_tv);
quantityTV.setText(number);
}
为什么代码 2 给出错误而代码 1 没有? b/w 代码 1 和 2 中存在 -“__”的区别
【问题讨论】:
-
代码 2 给出错误,因为 textview 需要 CharSequence 所以不能支持 int 值,代码 1 没有给出错误,因为 + 运算符会自动将其转换为字符串
-
这是因为在代码 1 中您说的是 setText( " " + number) ,这意味着您正在传递字符串,而在代码 2 中您说的是 setText(number) ,这意味着您正在传递的是 int 而不是 string .
-
@MaheshVayak 谢谢
-
@the_pooran 谢谢,明白你的意思要容易得多
标签: java android android-studio