java - Android 中使用 setText 的 id 问题

标签 java android

我在使用成绩百分比计算器时遇到问题。该项目有两个布局和两个 java 类。问题出在 First_Screen_J根据 logcat 的 Java 类。 logcat 是这样说的:

03-13 13:31:24.869 2167-2167/com.example.luke.percentagegradecalculator E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.luke.percentagegradecalculator, PID: 2167 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.luke.percentagegradecalculator/com.example.luke.percentagegradecalculator.First_Screen_J}: android.content.res.Resources$NotFoundException: String resource ID #0x13

Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x13 at android.content.res.Resources.getText(Resources.java:312) at android.widget.TextView.setText(TextView.java:4417) at com.example.luke.percentagegradecalculator.First_Screen_J.onCreate(First_Screen_J.java:79) at android.app.Activity.performCreate(Activity.java:6237)

 

public class First_Screen_J extends Activity {

    int MaxInt;
    String number = null;

    private TextView TV1;
    ....
    private TextView TV24;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstscreenx);

        TV1 = (TextView) findViewById(R.id.textView);
        ....
        TV24 = (TextView) findViewById(R.id.textView24);

        Bundle extras = getIntent().getExtras();
        if (extras != null){
            number = extras.getString("Number");
        }

        MaxInt = Integer.parseInt(number);
        TV1.setText(MaxInt - 1); // << --- Line Number 79 --- >>
        ...
        TV8.setText(MaxInt - 8);
        TV9.setText((int) Math.round((MaxInt - 1) / MaxInt) + "%");
        ...
        TV16.setText((int) Math.round((MaxInt - 8) / MaxInt) + "%");
    }
}

请帮助我!谢谢!

最佳答案

您误用了电视 1 -> 8 的 TextView.setText

TV1.setText(MaxInt - 1);

出现这种情况的原因是您正在使用

int x = MaxInt - 1;
TV1.setText( x );

来自Android Documentation for setText(int i)i 将是一个 ResourceID,一个 XML 文件中的字符串定义,将使用 R.string.text_for_tv1 或其他内容进行引用。

要解决这个问题,只需使用 setText(CharSequence cs) ,通过在前面添加 ""+

将您的值转换为字符串
TV1.setText("" + MaxInt - 1);

或者

 TV1.setText(Integer.toString(MaxInt - 1));

您似乎试图显示数字19,它是转换后的十六进制值0x13。抛出错误是因为在 XML 中未找到 ID 为 0x13 的字符串值。

其余的 textvews 可以正常工作,因为整数后面有 + "%",如果不存在,您也会遇到同样的问题。

关于java - Android 中使用 setText 的 id 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35975604/

相关文章:

java - ViewPagerAdapter 在 Fragment 中无法正常显示

设置 jFrame.setUndecorated(true) 时不调用 Java WindowClosing 事件

java - 找不到错误 : cannot access AnimatedImage class file for com. facebook.imagepipeline.animated.base.AnimatedImage

java - (Java) 组件未显示在面板上

java - 具有历史 API 的 Wicket AjaxEventBehavior

java - 您建议如何过滤包含在巨大列表中定义的冒犯性词语的评论

android - Android NDK 中静态库和共享库的区别?

Android SeekBarPreference 自定义 View

android - 干净地退出android应用程序

android - 仅向一个应用程序发送广播 Intent ,而不使用显式 Intent