You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

切换至ShareMedia布局时应用崩溃,ClassCastException问题求助

Android应用切换到ShareMedia布局时崩溃的排查与解决

崩溃日志

2022-07-29 21:42:03.128 24303-24303/com.example.newcadviewerapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.newcadviewerapp, PID: 24303
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newcadviewerapp/com.example.newcadviewerapp.ShareMedia}: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageView cannot be cast to android.widget.Button
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3729)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3896)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2326)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:263)
at android.app.ActivityThread.main(ActivityThread.java:8296)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)
Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageView cannot be cast to android.widget.Button
at com.example.newcadviewerapp.ShareMedia.onCreate(ShareMedia.kt:28)
at android.app.Activity.performCreate(Activity.java:8153)
at android.app.Activity.performCreate(Activity.java:8137)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1310)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3698)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3896) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:100) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2326) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:263) 
at android.app.ActivityThread.main(ActivityThread.java:8296) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1006)

相关文件内容

share_photo2.xml布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/app_bar"
        android:background="@android:color/white"
        >
        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginTop="2dp"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:id="@+id/profile_toolbar">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:id="@+id/close_share_post_button"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:contentDescription="@string/to_decline_share_post"
                    android:src="@drawable/cross">

                </ImageView>

                <ImageView
                    android:id="@+id/share_post_buttom"
                    android:layout_width="40dp"
                    android:layout_height="40dp"
                    android:layout_alignParentEnd="true"
                    android:layout_marginTop="5dp"
                    android:layout_marginEnd="10dp"
                    android:contentDescription="@string/share_the_post_into_feed"
                    android:src="@drawable/tick">

                </ImageView>

            </RelativeLayout>

        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_below="@id/app_bar">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:id="@+id/image_preview"
            android:src="@drawable/add_image_icon"
            android:scaleType="centerCrop"
            android:layout_marginTop="10dp"
            android:contentDescription="@string/preveiw_of_the_image_to_be_posted">

        </ImageView>

        <EditText
            android:id="@+id/post_description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="5dp"
            android:layout_marginTop="10dp"
            android:hint="@string/say_something_about_the_post"
            android:inputType="text"
            android:minHeight="48dp"
            android:textColorHint="#757575"
            android:autofillHints="">

        </EditText>

    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true">

        <include layout="@layout/bottom_nav" />
    </RelativeLayout>
</RelativeLayout>

bottom_nav.xml布局文件

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="55dp"

        >

        <ImageButton
            android:id="@+id/add_picture_button_bottomnav"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginTop="4dp"
            android:layout_marginEnd="44dp"
            android:contentDescription="@string/add_pictures"
            app:layout_constraintEnd_toStartOf="@+id/imageButton3"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@android:drawable/ic_input_add" />

        <ImageButton
            android:id="@+id/search_button_bottomnav"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginTop="4dp"
            android:layout_weight="1"
            android:contentDescription="@string/search_for_recruiter_and_peers"
            app:layout_constraintEnd_toStartOf="@+id/add_picture_button_bottomnav"
            app:layout_constraintHorizontal_bias="0.4"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@android:drawable/ic_menu_search" />

        <ImageButton
            android:id="@+id/imageButton3"
            android:layout_width="54dp"
            android:layout_height="50dp"
            android:layout_marginTop="4dp"
            android:layout_marginEnd="52dp"
            android:contentDescription="@string/profile_page"
            android:scaleType="fitCenter"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@drawable/img_1" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</merge>

ShareMedia.kt代码文件

package com.example.newcadviewerapp

import android.app.Activity
import android.app.Instrumentation
import android.media.Image
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity

import androidx.viewpager2.widget.ViewPager2
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference

import com.squareup.picasso.Picasso

class ShareMedia: AppCompatActivity() {
    lateinit var viewPager2: ViewPager2
    lateinit var storagePostPicRef : StorageReference
    private lateinit var image_preview : ImageView
    lateinit var share_post_buttom:Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.share_photo2)
        image_preview=findViewById(R.id.image_preview)
        share_post_buttom=findViewById(R.id.share_post_buttom)

        val contract=registerForActivityResult(ActivityResultContracts.GetContent()){     // 获取图片的uri
            image_preview.setImageURI(it)
        }

        storagePostPicRef=FirebaseStorage.getInstance().reference.child("Post Pictures")

        image_preview.setOnClickListener ()
        {
            contract.launch("image/*")
        }


    }

}

AndroidManifest.xml清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.newcadviewerapp">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CAMERA"/>



    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NewCADViewerApp">
        <activity
            android:name=".LoginActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>
        <activity android:name=".JoinActivity"/>
        <activity android:name=".MainActivity"/>
        <activity android:name=".RecruiterProfile"/>
        <activity android:name=".ShareMedia">

        </activity>



    </application>


</manifest>

问题原因

日志明确显示崩溃根源是类型转换异常:在ShareMedia.kt第28行,代码尝试将AppCompatImageView实例强制转换为Button类型。

对应代码与布局的矛盾点:

  • 在share_photo2.xml中,@+id/share_post_buttom是ImageView控件
  • 在ShareMedia.kt中,share_post_buttom被声明为Button类型,执行findViewById时触发类型转换错误

解决方案

有两种修复方式,任选其一即可:

方式一:修改Kotlin代码中的控件类型

将ShareMedia.kt里的share_post_buttom类型从Button改为ImageView:

// 原代码
lateinit var share_post_buttom:Button
// 修改后
lateinit var share_post_buttom:ImageView

方式二:修改布局文件中的控件类型

如果需要该控件具备按钮交互特性,推荐将share_photo2.xml中的ImageView改为ImageButton(更适合按钮交互场景):

<!-- 原代码 -->
<ImageView
    android:id="@+id/share_post_buttom"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="10dp"
    android:contentDescription="@string/share_the_post_into_feed"
    android:src="@drawable/tick">
</ImageView>

<!-- 修改后 -->
<ImageButton
    android:id="@+id/share_post_buttom"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_alignParentEnd="true"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="10dp"
    android:contentDescription="@string/share_the_post_into_feed"
    android:src="@drawable/tick"
    android:background="@null"> <!-- 移除默认按钮背景,仅显示图标 -->
</ImageButton>

同时需确保Kotlin代码中的类型与修改后的控件一致(改为ImageButton后,代码中要对应修改为lateinit var share_post_buttom:ImageButton)

内容的提问来源于stack exchange,提问作者Sanmoy Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 14:06:19