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

Kotlin中Fragment调用LayoutManager时RecyclerView崩溃求助

问题

在Android Studio中使用Kotlin开发时,Fragment内的RecyclerView从PlanetPopulator对象获取数据并在主Activity展示,应用持续闪退/崩溃且无错误提示,推测问题出在HomeFragment调用LinearLayoutManager的环节。

代码清单

Planets.kt

package com.example.rojenjohn

import android.os.Parcel
import android.os.Parcelable

//单数形式为Planet
data class Planets (var imageResourceID: Int,
                    var title: String?,
                    var galaxy: String?,
                    var link: String?,
                    var distance: Float,
                    var gravity: Float,
                    var overview: String?
):Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readInt(),
        parcel.readString(),
        parcel.readString(),
        parcel.readString(),
        parcel.readFloat(),
        parcel.readFloat(),
        parcel.readString()
    ) {
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeInt(imageResourceID)
        parcel.writeString(title)
        parcel.writeString(galaxy)
        parcel.writeString(link)
        parcel.writeFloat(distance)
        parcel.writeFloat(gravity)
        parcel.writeString(overview)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<Planets> {
        override fun createFromParcel(parcel: Parcel): Planets {
            return Planets(parcel)
        }

        override fun newArray(size: Int): Array<Planets?> {
            return arrayOfNulls(size)
        }
    }
}

MyAdapter.kt

package com.example.rojenjohn

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.list_item.view.*

class MyAdapter (private val planetsList : List<Planets>) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val titleHolder = itemView.planet_title
        val galaxyHolder = itemView.planet_galaxy
        val distanceHolder = itemView.planet_distance
        val gravityHolder = itemView.planet_gravity
        val imageHolder = itemView.planet_img
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyAdapter.MyViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
        return MyViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val planetItem = planetsList[position]

        holder.titleHolder.text = planetItem.title
        holder.galaxyHolder.text = planetItem.galaxy
        holder.distanceHolder.text = String.format("%.2f km", planetItem.distance)
        holder.gravityHolder.text = String.format("%.2f m/s/s", planetItem.gravity)
        holder.imageHolder.setImageResource(planetItem.imageResourceID)

        /*使用Lambda表达式
        holder.itemView.setOnClickListener { v ->
            val activity = v!!.context as AppCompatActivity

            //传递planetItem对象 > 未通过Parcelable/Serializable逐个传递

            val bundle = Bundle()
            // 这样写是否正确?
            bundle.putInt("planet_imgBundle", planetItem.imageResourceID);
            bundle.putString("planet_titleBundle", planetItem.title)
            bundle.putString("planet_galaxyBundle", planetItem.galaxy)
            bundle.putString("planet_linkBundle", planetItem.link)
            bundle.putString("planet_distanceBundle", planetItem.distance)
            bundle.putString("planet_gravityBundle", planetItem.gravity)
            bundle.putString("planet_overviewBundle", planetItem.overview)

            val detailFragment = DetailFragment()
            detailFragment.arguments = bundle

            activity.supportFragmentManager.beginTransaction()
                .replace(R.id.frame_layout, detailFragment).addToBackStack(null).commit()
        } */
    }

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

MainActivity.kt

package com.example.rojenjohn

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        replaceFragment(HomeFragment())
        //设置首页Fragment/初始Fragment
    }

    private fun replaceFragment(homeFragment: HomeFragment){
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.frame_layout, homeFragment)
        fragmentTransaction.commit()
    }
}

HomeFragment.kt

package com.example.rojenjohn

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

private lateinit var adapter: MyAdapter
private lateinit var recyclerView: RecyclerView

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // 填充Fragment布局
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val layoutManager = LinearLayoutManager(context)
        recyclerView = view.findViewById(R.id.recycler_view)
        recyclerView.layoutManager = layoutManager
        recyclerView.setHasFixedSize(true)
        adapter = MyAdapter(PlanetPopulator.setPlanets())
        recyclerView.adapter = adapter
    }
}

PlanetPopulator.kt(单例对象)

package com.example.rojenjohn

object PlanetPopulator {
    fun setPlanets(): List<Planets> {
        val planetList = mutableListOf<Planets>()
        planetList.add(
            Planets(
                1,
                "Mars",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Mars",
                227.9f,
                3.721f,
                "Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury. In English, Mars carries the name of the Roman god of war and is often referred to as the \"Red Planet\".\nThe latter refers to the effect of the iron oxide prevalent on Mars's surface, which gives it a reddish appearance distinctive among the astronomical bodies visible to the naked eye.\nMars is a terrestrial planet with a thin atmosphere, with surface features reminiscent of the impact craters of the Moon and the valleys, deserts and polar ice caps of Earth."
            )
        )
        planetList.add(
            Planets(
                2,
                "Moon",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Moon",
                150.0f,
                1.62f,
                "The Moon is Earth's only natural satellite. At about one-quarter the diameter of Earth (comparable to the width of Australia), it is the largest natural satellite in the Solar System relative to the size of its planet, the fifth largest satellite in the Solar System overall, and is larger than any dwarf planet.\nOrbiting Earth at an average distance of 384,400 km (238,900 mi), or about 30 times Earth's diameter, its gravitational influence slightly lengthens Earth's day and is the main driver of Earth's tides. The Moon is classified as a planetary-mass object and a differentiated rocky body, and lacks any significant atmosphere, hydrosphere, or magnetic field.\nIts surface gravity is about one-sixth of Earth's (0.1654 g); Jupiter's moon Io is the only satellite in the Solar System known to have a higher surface gravity and density."
            )
        )
        planetList.add(
            Planets(
                3,
                "Neptune",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Neptune",
                4497.1f,
                11.15f,
                "Neptune is the eighth and farthest-known Solar planet from the Sun. In the Solar System, it is the fourth-largest planet by diameter, the third-most-massive planet, and the densest giant planet.\n It is 17 times the mass of Earth, slightly more massive than its near-twin Uranus. Neptune is denser and physically smaller than Uranus because its greater mass causes more gravitational compression of its atmosphere. The planet orbits the Sun once every 164.8 years at an average distance of 30.1 AU (4.5 billion km; 2.8 billion mi).\nIt is named after the Roman god of the sea and has the astronomical symbol ♆, a stylised version of the god Neptune's trident."
            )
        )
        planetList.add(
            Planets(
                4,
                "Earth",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Earth",
                149.6f,
                9.807f,
                "Earth is the third planet from the Sun and the only astronomical object known to harbor and support life. About 29.2% of Earth's surface is land consisting of continents and islands. The remaining 70.8% is covered with water, mostly by oceans, seas, gulfs, and other salt-water bodies, but also by lakes, rivers, and other freshwater, which together constitute the hydrosphere.\n Much of Earth's polar regions are covered in ice. Earth's outer layer is divided into several rigid tectonic plates that migrate across the surface over many millions of years, while its interior remains active with a solid iron inner core, a liquid outer core that generates Earth's magnetic field, and a convective mantle that drives plate tectonics."
            )
        )
        planetList.add(
            Planets(
                5,
                "Venus",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Venus",
                108.2f,
                8.87f,
                "Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty. As the brightest natural object in Earth's night sky after the Moon, Venus can cast shadows and can be, on rare occasions, visible to the naked eye in broad daylight.\n Venus lies within Earth's orbit, and so never appears to venture far from the Sun, either setting in the west just after dusk or rising in the east a little while before dawn. Venus orbits the Sun every 224.7 Earth days.\n With a rotation period of 243 Earth days, it takes significantly longer to rotate about its axis than any other planet in the Solar System, and does so in the opposite direction to all but Uranus (meaning the Sun rises in the west and sets in the east). Venus does not have any moons, a distinction it shares only with Mercury among the planets in the Solar System."
            )
        )
        planetList.add(
            Planets(
                6,
                "Uranus",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Uranus",
                2871.0f,
                8.87f,
                "Uranus is the seventh planet from the Sun. Its name is a reference to the Greek god of the sky, Uranus, who, according to Greek mythology, was the great-grandfather of Ares (Mars), grandfather of Zeus (Jupiter) and father of Cronus (Saturn).\nIt has the third-largest planetary radius and fourth-largest planetary mass in the Solar System. Uranus is similar in composition to Neptune, and both have bulk chemical compositions which differ from that of the larger gas giants Jupiter and Saturn. For this reason, scientists often classify Uranus and Neptune as \"ice giants\" to distinguish them from the other gas giants.\nUranus's atmosphere is similar to Jupiter's and Saturn's in its primary composition of hydrogen and helium, but it contains more \"ices\" such as water, ammonia, and methane, along with traces of other hydrocarbons. It has the coldest planetary atmosphere in the Solar System."
            )
        )
        planetList.add(
            Planets(
                7,
                "Sun",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Sun",
                0f,
                274.0f,
                "The Sun is the star at the center of the Solar System. It is a nearly perfect sphere of hot plasma, heated to incandescence by nuclear fusion reactions in its core, radiating the energy mainly as visible light and infrared radiation. It is by far the most important source of energy for life on Earth. Its diameter is about 1.39 million kilometres (864,000 miles), or 109 times that of Earth. Its mass is about 330,000 times that of Earth; it accounts for about 99.86% of the total mass of the Solar System.\nRoughly three quarters of the Sun's mass consists of hydrogen (~73%); the rest is mostly helium (~25%), with much smaller quantities of heavier elements, including oxygen, carbon, neon and iron."
            )
        )
        planetList.add(
            Planets(
                8,
                "Saturn",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Saturn",
                1427.0f,
                10.44f,
                "Saturn is the sixth planet from the Sun and the second-largest in the Solar System, after Jupiter. It is a gas giant with an average radius of about nine and a half times that of Earth.\n It only has one-eighth the average density of Earth; however, with its larger volume, Saturn is over 95 times more massive. Saturn is named after the Roman god of wealth and agriculture; its astronomical symbol (♄) represents the god's sickle.\n The Romans named the seventh day of the week Saturday, Sāturni diēs (\"Saturn's Day\") no later than the 2nd century for the planet Saturn."
            )
        )
        planetList.add(
            Planets(
                9,
                "Jupiter",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Jupiter",
                778.3f,
                24.79f,
                "Jupiter is the fifth planet from the Sun and the largest in the Solar System. It is a gas giant with a mass (more than) two and a half times that of all the other planets in the Solar System combined, but (a little) less than one-thousandth the mass of the Sun.\nJupiter is the third-brightest natural object in the Earth's night sky after the Moon and Venus. It has been observed since pre-historic times and is named after the Roman god Jupiter, the king of the gods, because of its massive size"
            )
        )
        planetList.add(
            Planets(
                10,
                "Mercury",
                "Milkyway Galaxy",
                "https://en.wikipedia.org/wiki/Mercury",
                57.9f,
                3.7f,
                "Mercury is the smallest planet in the Solar System and the closest to the Sun. Its orbit around the Sun takes 87.97 Earth days, the shortest of all the Sun's planets. It is named after the Roman god Mercurius (Mercury), god of commerce, messenger of the gods, and mediator between gods and mortals, corresponding to the Greek god Hermes (Ἑρμῆς).\nLike Venus, Mercury orbits the Sun within Earth's orbit as an inferior planet, and its apparent distance from the Sun as viewed from Earth never exceeds 28°.\nThis proximity to the Sun means the planet can only be seen near the western horizon after sunset or the eastern horizon before sunrise, usually in twilight. At this time, it may appear as a bright star-like object but is often far more difficult to observe than Venus.\nFrom Earth, the planet telescopically displays the complete range of phases, similar to Venus and the Moon, which recurs over its synodic period of approximately 116 days."
            )
        )
        return planetList
    }
}
分析与修复方案

1. 核心崩溃原因:无效图片资源ID

PlanetPopulator中给imageResourceID传入的是1、2这类硬编码数字,而Android的资源ID是R.drawable.xxx生成的唯一整数,直接使用1会导致setImageResource找不到对应资源,触发Resources.NotFoundException引发崩溃。
修复:
将PlanetPopulator中的imageResourceID替换为实际的drawable资源ID,示例:

// 假设你已将对应星球图片放入drawable文件夹
Planets(
    R.drawable.mars,
    "Mars",
    "Milkyway Galaxy",
    ...
)

2. 优化Fragment变量声明

HomeFragment中的recyclerView和adapter被声明为全局private lateinit,Fragment生命周期内全局变量易引发内存泄漏或空指针问题,应改为Fragment成员变量,同时用requireContext()替代context确保获取非空Context:
修复HomeFragment.kt:

class HomeFragment : Fragment() {
    // 改为Fragment成员变量
    private lateinit var adapter: MyAdapter
    private lateinit var recyclerView: RecyclerView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_home, container, false
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:36:14