【问题标题】:java.lang.ClassCastException: java.lang.Integer cannot be cast to android.widget.ImageButtonjava.lang.ClassCastException:java.lang.Integer 无法转换为 android.widget.ImageButton
【发布时间】:2021-03-14 20:10:57
【问题描述】:

所以我对 Kotlin 还很陌生。

我正在尝试在图像按钮上创建一个 onClickListener 以打开共享界面,以便可以通过 SMS 等方式共享来自 recyclerView 的特定视频。

当我尝试在片段中执行此操作时,我遵循了有关如何执行此操作的各种教程,当我尝试打开相关片段时,应用程序不断崩溃。

我收到以下错误

java.lang.ClassCastException: java.lang.Integer cannot be cast to android.widget.ImageButton

这是我的片段代码的样子:

SearchFragment.kt

class SearchFragment : Fragment(), View.OnClickListener
{

    private var layoutManager: RecyclerView.LayoutManager? = null
    private var adapter: RecyclerView.Adapter<ClipAdapter.ViewHolder>? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View
    {
        val rootView = inflater.inflate(R.layout.fragment_search, container, false)
        loadData()
        return rootView
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?)
    {
        val shareBtn = view.findViewById<ImageButton>(R.id.button_to_share)
        shareBtn.setOnClickListener(this)
    }

    private fun loadData()
    {
        val service = TwitchServiceBuilder.buildService(TwitchService::class.java)
        val requestCall = service.getClips("anerdfails")

        requestCall.enqueue(object : Callback<List<Clip>>
        {
            override fun onResponse(
                call: Call<List<Clip>>,
                response: Response<List<Clip>>
            )
            {
                if (response.isSuccessful)
                {
                    //process data
                    recyclerView.layoutManager = GridLayoutManager(activity, 2)
                    recyclerView.adapter = ClipAdapter(response.body()!!)
                } else
                {
                    //output alert
                    AlertDialog.Builder(activity!!)
                        .setTitle("API error")
                        .setMessage("Response, but something went wrong ${response.message()}")
                        .setPositiveButton(android.R.string.ok) { _, _ -> }
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show()
                }
            }

            override fun onFailure(call: Call<List<Clip>>, t: Throwable)
            {
                //process failure
                AlertDialog.Builder(activity!!)
                    .setTitle("API error")
                    .setMessage("No response, and something went wrong $t")
                    .setPositiveButton(android.R.string.ok) { _, _ -> }
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show()
            }
        })
    }

    override fun onClick(v: View?)
    {
        Toast.makeText(activity, "Its toast!", Toast.LENGTH_SHORT).show()
    }

}

这是我为 RecyclerView 设计的 2 个布局:

fragment_search.xml

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingStart="15dp"
    android:paddingTop="?attr/actionBarSize"
    android:paddingEnd="15dp"
    tools:context=".ui.search.SearchFragment">

    <androidx.appcompat.widget.SearchView
        android:background="@drawable/search_bar"
        android:id="@+id/clipSearch"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="5dp"
        android:focusable="true"
        android:focusableInTouchMode="true"
        app:layout_constraintBottom_toTopOf="@+id/recyclerView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="75dp"
        android:scrollbars="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/clipSearch" />

</androidx.constraintlayout.widget.ConstraintLayout>

clip_layout.xml

<?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:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".ui.search.SearchFragment">

    <VideoView
        android:id="@+id/videoClip"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintDimensionRatio="w,2:3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/videoClip"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/txtChannel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtTitle"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/txtGame"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtChannel"
        tools:ignore="HardcodedText" />

    <TextView
        android:id="@+id/txtViews"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/txtGame"
        tools:ignore="HardcodedText" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:orientation="horizontal"
        android:weightSum="2"
        android:layout_marginTop="15dp"
        app:layout_constraintTop_toBottomOf="@+id/txtViews">

        <ImageButton
            android:id="@+id/favouriteButton"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@null"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_baseline_favorite_border_24" />

        <ImageButton
            android:id="@+id/button_to_share"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@null"
            android:scaleType="fitCenter"
            android:src="@drawable/ic_baseline_share_24" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

这对我来说似乎是一个简单的错误,但我正在努力找出我做错了什么导致加载错误。

任何帮助将不胜感激。

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    我看到您试图在片段中找到“ShareBtn”按钮,这是完全错误的。 “ShareBtn”不属于片段,它属于您在“ClipAdapter”中创建的viewHolder 您需要做的是在“ClipAdapter”内创建一个接口,并在适配器内从它创建一个对象 然后调用clickListener应该将点击委托给它的方法 最后,您应该在片段中实现它并放置您想要的任何逻辑 This 链接将帮助您实现它

    【讨论】:

    • 绝对传奇,将 onClickListener 添加到我的适配器中的 ViewHolder 类中,并且 toast 消息按预期出现。
    • 很高兴能帮到你,你的评论让我很开心
    【解决方案2】:

    您正在将视图 ID(Integer)转换为 ImageButton(此行中的 View

    val shareBtn = R.id.button_to_share as ImageButton
    

    你应该改用这个

    val shareBtn = findViewById<ImageButton>(R.id.button_to_share)
    

    更新

    您还应该在创建片段视图后找到视图。这意味着您应该在 `onViewCreated` 中而不是在 `onCreateView` 中调用 `findViewById`。如果您尝试在创建片段视图之前查找视图,那么您会得到“NullPointerException”,因为还没有视图。

    【讨论】:

    • Brill,这样就修复了我遇到的初始错误。我现在收到一个新错误:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference - 简短的 Google 建议这可能是因为它位于内部布局文件中,而不是在 onCreateView() 方法上调用的那个。我将如何解决它?我也用布局代码更新了问题。
    • @E.Fitzpatrick 我已经更新了我的答案。看看它是否解决了您的问题:D
    • 我尝试了您的建议并将点击侦听器移动到 onViewCreated() 函数(有关更新代码,请参阅原始问题),但我仍然遇到相同的错误。 Logcat 指定错误来自这一行:shareBtn.setOnClickListener(this)
    猜你喜欢
    • 2015-12-30
    • 2018-03-16
    • 2020-07-22
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多