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

Android ExpandableListView夜间模式文字不变亮问题如何解决?

问题原因
  • 核心问题出在你创建SimpleExpandableListAdapter时传入的上下文参数,activity.getApplicationContext()是全局应用上下文,不会携带当前Activity的主题配置(包括深色模式的配色规则),所以加载列表项布局时默认沿用了系统浅色主题的黑色文字配置。
  • 次要可能原因是你自定义的groupLayout、childLayout布局文件中,TextView的文字颜色使用了硬编码的黑色色值,没有适配深色模式的主题属性。
解决方案

方案1:替换适配器的上下文参数(优先尝试,改一行代码即可)

把创建适配器时的第一个参数从全局ApplicationContext替换为当前Activity实例,Activity上下文会携带当前界面生效的主题配置,包括深色模式的配色:

// 把第一个参数的activity.getApplicationContext()替换为activity本身
ExpandableListAdapter adapter = new SimpleExpandableListAdapter(
            activity, 
            groupData, groupLayout, groupFrom, groupTo,
            childData, childLayout, childFrom, childTo);
ExpandableListView expandableListView = view.findViewById(R.id.my_expandable_list_view);
expandableListView.setAdapter(adapter);

方案2:修正列表项布局的颜色配置

如果替换上下文后仍有问题,检查你用到的groupLayout、childLayout布局文件,把其中TextView的android:textColor属性从硬编码的色值(比如#FF000000)替换为主题属性,系统会自动根据当前模式匹配颜色:

<!-- 示例:文字颜色使用系统主文本主题属性 -->
<TextView
    android:id="@+id/group_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="?android:attr/textColorPrimary" />

如果你需要自定义配色,可以在values/colors.xml和values-night/colors.xml中分别定义同名色值,布局中引用@color/你的色值名称即可自动适配。

方案3:自定义适配器手动设置颜色(特殊场景使用)

如果上述方案都不满足需求,可以重写SimpleExpandableListAdapter的getGroupView和getChildView方法,动态获取当前主题的文字颜色设置给控件:

SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(
        activity,
        groupData, groupLayout, groupFrom, groupTo,
        childData, childLayout, childFrom, childTo) {
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        View view = super.getGroupView(groupPosition, isExpanded, convertView, parent);
        TextView textView = view.findViewById(R.id.group_text_id);
        // 获取当前主题的主文本颜色
        TypedValue typedValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
        textView.setTextColor(typedValue.data);
        return view;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        View view = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
        TextView textView = view.findViewById(R.id.child_text_id);
        TypedValue typedValue = new TypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
        textView.setTextColor(typedValue.data);
        return view;
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:09:03