当我尝试执行代码并且应用程序也终止时,出现以下错误。 (引起:java.lang.ClassCastException:androidx.appcompat.widget.AppCompatTextView无法转换为android.widget.Button)
package com.tisu.role
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
@SuppressLint("WrongViewCast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rollButton: Button = findViewById(R.id.roll_button)
rollButton.setOnClickListener {
Toast.makeText(this, "button clicked", Toast.LENGTH_LONG).show()
}
}
}
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/roll_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/_01"
android:textSize="40sp"
android:layout_gravity="center_horizontal"
/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/roll"
/>
</LinearLayout>
最佳答案
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to android.widget.Button)
在您的布局中,roll_button
是一个TextView
,在您的 Activity 中,您尝试将findViewById
作为Button
这就是为什么你会得到 ClassCastException
First solution is
使用这个
val rollButton: TextView = findViewById(R.id.roll_button)
而不是这个
val rollButton: Button = findViewById(R.id.roll_button)
Second solution is
将 roll_button
ID 分配给布局文件中的按钮
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center_vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/_01"
android:textSize="40sp"
android:layout_gravity="center_horizontal"
/>
<Button android:layout_width="wrap_content"
android:id="@+id/roll_button"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/roll"
/>
</LinearLayout>
奖金
另请阅读此内容
在 kotlin 中无需findViewById
关于java - 如何修复由 : java. lang.ClassCastException : androidx. appcompat.widget.AppCompatTextView 无法转换为 android.widget.Button 引起的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56472025/