開發者在 MenuActivity 中點擊 ImageButton 後,將該 View 的 ID 透過 Intent.putExtra("id", v.getId()) 傳遞給 SuperheroActivity。但在接收端直接調用 textView.setText(id) 時,畫面顯示為資源 ID 的整數值(如 2131230723),而非預期的文字內容,甚至出現 "false" 提示。
TextView.setText(int) 方法被識別為「設置字串資源 ID」而非「顯示數字」。當傳入的整數不是有效的字串資源 ID 時,系統會嘗試查找對應資源,找不到則顯示空白或異常值。正確做法是將整數轉為字串後再設置。
// SuperheroActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_superhero);
Intent intent = getIntent();
int viewId = intent.getIntExtra("id", 0); // 獲取傳遞的 View ID
TextView textView = findViewById(R.id.superheroText);
// 錯誤寫法:textView.setText(viewId);
// 正確寫法:轉為字串
textView.setText(String.valueOf(viewId));
// 或 textView.setText("" + viewId);
// 或 textView.setText(Integer.toString(viewId));
}
直接傳遞 View ID(如 R.id.superman)耦合度高且無語義。建議改用字串常量或枚舉:
// 發送端
intent.putExtra("hero_type", "superman");
// 接收端
String hero = intent.getStringExtra("hero_type");
textView.setText(hero); // 直接顯示 "superman" 或映射後的中文名
此方式解耦介面元素與業務邏輯,方便後續維護與國際化。
TextView.setText(int) 尋找字串資源,非顯示數字。String.valueOf(int) 或 Integer.toString(int)。