有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java需要帮助理解logcat消息ClassCastException

    final EditText edt =findViewById(R.id.type_text);
    final TextView txt= findViewById(R.id.empty_text);
    Button   btn =      findViewById(R.id.button_add);
    final String value = edt.getText().toString();

    btn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            txt.append(value+"\n");
            edt.setText("");
        }
    });

这是第40行-->;最终编辑文本edt=findViewById(R.id.type_text)

Logcat消息
Caused by: java.lang.ClassCastException: 安卓.support.design.widget.TextInputLayout cannot be cast to 安卓.widget.EditText at com.example.todo.activitity2.onCreate(activitity2.java:40)


共 (2) 个答案

  1. # 1 楼答案

    在布局XML文件中,有ID为type_textTextInputLayout,您正试图将其转换为EditText

    在XML文件中,将此文本输入布局更改为编辑文本

    在你们班。java文件更正此错误: final EditText edt = findViewById(R.id.type_text);

    final TextInputLayout your_name = findViewById(R.id.type_text);

  2. # 2 楼答案

    您需要更改以下内容:

    final EditText edt = findViewById(R.id.type_text);
    

    进入适当的类:(R.id.type_text为TextInputLayout,您将其创建为EditText,这就是导致执行的原因)

    final TextInputLayout edt = findViewById(R.id.type_text);