【问题标题】:Android studio app keeps on crashing and showing screen cast errorAndroid Studio 应用程序不断崩溃并显示屏幕投射错误
【发布时间】:2019-11-27 12:07:07
【问题描述】:

引起:java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout 不能被强制转换为 android.widget.EditTextat com.example.login.MainActivity.onCreate(MainActivity.kt:18) 在 android.app.Activity.performCreate(Activity.java:7009) 在 android.app.Activity.performCreate(Activity.java:7000) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 在 android.app.ActivityThread.-wrap11(未知来源:0) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java:6494) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

这是我出现错误的 kotlin 代码:

val Name = findViewById<EditText>(R.id.etName)

val Password = findViewById<EditText>(R.id.etpassword)

val Login = findViewById<Button>(R.id.btnlogin)

val Info = findViewById<TextView>(R.id.tvinfo)

?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"    
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/etName"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

【问题讨论】:

  • 你也可以粘贴你的布局xml吗?
  • ?xml version="1.0" encoding="utf-8"?> schemas.android.com/apk/res/android" xmlns:app="schemas.android.com/apk/res-auto" xmlns:tools="schemas.android.com/tools" android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

标签: android kotlin androidx


【解决方案1】:

看起来你有

android:id="@+id/etName"

在你的根目录ConstraintLayout。在代码中你有

val Name = findViewById<EditText>(R.id.etName)

它通过 id etName 找到一个视图并尝试将其转换为 EditTextfindViewById() 中的算法只是一个简单的树搜索,它在第一次匹配时停止,这是您的根布局。如果您有另一个具有相同 ID 的视图(例如您的 EditText),则搜索永远不会达到那么深。砰,ClassCastException.

要修复它,请从根布局中删除 id,或将其更改为布局文件中的唯一内容,并确保布局中确实有一个 EditText 和 id etName

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2013-03-16
    • 2022-06-13
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多