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

应用主题与系统不一致时GridLayout动态加载异常求助

GridLayout动态元素仅在应用与系统主题一致时显示,主题不一致时加载异常

当Android应用主题与手机系统主题不一致时,GridLayout中动态生成的卡片元素无法显示;仅当应用与系统主题同为浅色或同为深色时,元素才能正常显示。

布局代码(GridLayout)

<GridLayout
        android:id="@+id/gridLayoutMainPage"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_marginStart="5dp"
        android:layout_marginEnd="5dp"
        android:alignmentMode="alignMargins"
        android:columnCount="2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/view5"
        app:layout_constraintVertical_bias="0.5" />

动态生成卡片的函数代码

fun generateCards(cards : List<CardDataHolder>, gridLayout: GridLayout) {
        for (card in cards) {
            val cardview: View = LayoutInflater.from(context)
                .inflate(R.layout.item_main_page_cardview, gridLayout, false)
            val params = GridLayout.LayoutParams()
            params.width = GridLayout.LayoutParams.WRAP_CONTENT;
            params.height = GridLayout.LayoutParams.WRAP_CONTENT;
            params.setMargins(10, 25, 10, 25);
            cardview.layoutParams = params;
            cardview.findViewById<TextView>(R.id.title_card_main_page).text = card.title
            cardview.findViewById<ImageView>(R.id.icon_card_main_page).setImageResource(card.icon)

            cardview.setOnClickListener(View.OnClickListener {
                switchFragment(card.fragment)
                card.fragment.view?.invalidate()
            })

            gridLayout.addView(cardview);
        }
    }

已尝试的解决方案

  • 主题切换后重新验证视图
  • 将主题切换时机调整至所有元素初始化完成后

以上方法均未解决问题。

状态说明

  • 正确状态(应用与系统主题一致):GridLayout中两行两列的卡片正常显示,布局居中排列
  • 异常状态(应用与系统主题不一致):GridLayout所在区域为空,无任何动态生成的卡片元素

希望有人能帮忙解决这个问题,谢谢!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 08:24:58