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

Android Kotlin应用启动后闪退问题排查求助

问题排查与修复方案

你的App启动闪退核心原因是RecyclerView Adapter未实现关键方法,以及缺少必要的列表项布局文件,以下是具体修复步骤:


1. 核心错误分析

  • MyAdapter.kt中的onCreateViewHolder和addColumn方法使用了TODO(),这是Kotlin的占位符函数,调用时会直接抛出NotImplementedError异常。虽然启动时列表为空不会立即触发,但隐性场景或后续操作会直接导致崩溃。
  • 缺少RecyclerView的列表项布局文件,ViewHolder中引用的android.R.id.text1没有对应的布局载体,即使实现方法也会引发空指针异常。
  • 若未在依赖中添加RecyclerView库,布局解析阶段就会失败,直接导致启动闪退。

2. 具体修复步骤

步骤1:创建RecyclerView列表项布局

在res/layout目录下新建item_column.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:textSize="16sp" />

步骤2:修复MyAdapter.kt的完整实现

package com.example.erstesachenso

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class MyAdapter : RecyclerView.Adapter<MyAdapter.ViewHolder>() {

    private val columns = mutableListOf<String>()

    override fun onBindViewHolder(holder: ViewHolder, position: Int){
        val columnName = columns[position]
        holder.bind(columnName)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        // 加载自定义列表项布局
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_column, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return columns.size
    }

    fun addColumn(columnName: String) {
        columns.add(columnName)
        // 通知RecyclerView插入新数据
        notifyItemInserted(columns.size - 1)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val textViewColumn: TextView = itemView.findViewById(android.R.id.text1)

        fun bind(columnName: String) {
            textViewColumn.text = columnName
        }
    }
}

步骤3:确认RecyclerView依赖

在Module级build.gradle(通常是app/build.gradle)的dependencies块中添加依赖:

implementation 'androidx.recyclerview:recyclerview:1.3.2'

步骤4:检查Activity注册

确保AndroidManifest.xml中MainActivity已正确注册:

<activity
    android:name=".MainActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

完成以上操作后,App即可正常启动,点击按钮添加的内容会正确显示在RecyclerView中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:02:13