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

ScrollView检测到多个直接子视图错误的排查与解决请求

解决ScrollView只能有一个直接子View的错误

问题根源

你的fragment_course.xml中,ScrollView已经包含了一个id为containerLayout的LinearLayout作为直接子View,但在CourseFragment.kt中,你又新建了一个LinearLayout并调用scrollView.addView(linearLayout),这就导致ScrollView同时拥有两个直接子View,触发系统抛出的IllegalStateException。

解决方法

直接复用xml中已有的containerLayout,不需要新建LinearLayout并添加到ScrollView:

修改后的CourseFragment.kt代码

package com.example.assignment.ui.courses

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.assignment.databinding.FragmentCourseBinding
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase

class CourseFragment : Fragment() {

    private var _binding: FragmentCourseBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val courseViewModel =
            ViewModelProvider(this).get(CourseViewModel::class.java)

        _binding = FragmentCourseBinding.inflate(inflater, container, false)
        val root: View = binding.root

        // 直接使用xml中已有的containerLayout
        val containerLayout = binding.containerLayout

        // 从Firestore获取数据
        val db = Firebase.firestore
        db.collection("course")
            .get()
            .addOnSuccessListener { documents ->
                for (document in documents) {
                    // 为每个文档创建TextView
                    val textView = TextView(context)
                    textView.text = document.data.toString()

                    // 将TextView添加到已有的LinearLayout中
                    containerLayout.addView(textView)
                }
            }
            .addOnFailureListener { exception ->
                Log.w("Not Found", "Error getting documents: ", exception)
            }

        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

额外优化建议

  • 给动态添加的TextView设置布局参数,提升界面美观度:
    val layoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
    )
    layoutParams.setMargins(16, 16, 16, 0)
    textView.layoutParams = layoutParams
    
  • 若要避免Fragment重建时重复添加数据,可在添加前清空容器:containerLayout.removeAllViews()

内容的提问来源于stack exchange,提问作者NG CHUN KIAT JACK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:17:02