首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android TextView.setText(int) 崩潰:整數被誤認為資源 ID

     編輯:程式設計綜合問答

錯誤現象

text.setText(hourOfDay); // hourOfDay 為 int
// logcat: Exception dispatching input event / Resources$NotFoundException

TextView.setText(int) 會嘗試將參數視為字串資源 ID(R.string.xxx),找不到對應資源則拋出 Resources$NotFoundException。

修正方法

text.setText(Integer.toString(hourOfDay));
// 或
text.setText(String.valueOf(hourOfDay));
// 或
text.setText(hourOfDay + "");

將整數明確轉為 String 呼叫 setText(CharSequence) 多載。

避坑指南

  • 所有 View.setText(int) 均視為資源 ID,若需顯示數值,必須先轉字串。
  • Kotlin 擴充函數 text.text = hourOfDay.toString() 同理。
  • 使用 String.format 可同時格式化:text.setText(String.format("%02d:%02d", hour, min))。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved