问题描述:java.lang.ClassCastException: androidx.constraintlayout.widget.ConstraintLayout cannot be cast to android.widget.TextView
问题分析:这是因为对于ConstraintLayout和textView,布局XML文件具有相同的id msg。因此,在代码中使用R.id.msg引用textView时,它会链接到ConstraintLayout,从而导致ClassCast异常。
修改前:
<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/msg"
tools:context=".MainActivity"
tools:visibility="visible"
style="@style/mymsg">
修改后:
<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/constraint_layout"
tools:context=".MainActivity"
tools:visibility="visible"
style="@style/mymsg">