You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android点击按钮生成随机字符设置到TextView时应用崩溃求助

问题原因

崩溃的核心原因是调用TextView.setText(char)时,系统会将char自动转换为int,当作字符串资源ID去查找对应资源,但你生成的字符对应的int值(比如'A'对应65)并不存在于资源文件中,因此抛出Resources$NotFoundException导致应用崩溃。

修复方案

需要将char类型的字符转换为String类型后再设置给TextView,以下是两种简单实现方式:

方式一:将char转为String

修改设置文本的代码:

noteQuestion.setText(String.valueOf(note));

或者用字符串拼接的方式:

noteQuestion.setText("" + note);

方式二:直接生成String类型的随机字符

直接从原字符串中截取单个字符的子串,避免char类型的转换问题:

int randomIndex = rnd.nextInt(characterString.length());
String randomChar = characterString.substring(randomIndex, randomIndex + 1);
noteQuestion.setText(randomChar);
完整修复后的代码
public void startGame (View starGame) {
    String characterString = "ABCDE";
    Random rnd = new Random();
    char note = characterString.charAt(rnd.nextInt(characterString.length()));
    TextView noteQuestion = findViewById(R.id.CharacterOutput); 
    noteQuestion.setText(String.valueOf(note)); // 修复为传入String类型
}

内容的提问来源于stack exchange,提问作者Dusty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:21:00