Android中AlertDialog调用setSingleChoiceItems未显示全部单选按钮怎么办
修复方案
这个问题的核心原因是未选中状态的单选按钮颜色和AlertDialog的背景色重合,导致视觉上不可见,可通过以下任意一种方案修复:
- 方案1:显式指定AlertDialog的适配主题
构建Builder时传入MaterialComponents兼容的Alert主题,确保单选按钮的默认颜色和背景有足够对比度:// 需确保项目已引入MaterialComponents依赖 AlertDialog.Builder b = new AlertDialog.Builder(Activity.this, R.style.Theme_MaterialComponents_DayNight_Dialog_Alert); String[] types = getResources().getStringArray(R.array.text_spinner_NewClass_dayList); b.setSingleChoiceItems(types, 2, (dialog, which) -> { textView.setText(types[which]); dialog.dismiss(); } ); b.show(); - 方案2:自定义单选列表项布局
手动指定单选按钮的颜色,避免和背景重合:- 新建布局文件
res/layout/dialog_single_choice_item.xml
<CheckedTextView 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:paddingVertical="16dp" android:paddingHorizontal="20dp" android:checkMark="?android:attr/listChoiceIndicatorSingle" android:checkMarkTint="@color/design_default_color_primary" <!-- 替换为你项目里合适的颜色 --> android:textSize="16sp"/>- 代码中传入自定义布局的适配器
AlertDialog.Builder b = new AlertDialog.Builder(Activity.this); String[] types = getResources().getStringArray(R.array.text_spinner_NewClass_dayList); ArrayAdapter<String> adapter = new ArrayAdapter<>(Activity.this, R.layout.dialog_single_choice_item, types); b.setSingleChoiceItems(adapter, 2, (dialog, which) -> { textView.setText(types[which]); dialog.dismiss(); } ); b.show(); - 新建布局文件
- 方案3:修改全局主题属性
在你的Activity使用的主题中添加colorControlNormal属性配置,统一修改未选中状态控件的颜色:<style name="YourAppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar"> <!-- 其他主题配置 --> <item name="colorControlNormal">@color/gray_600</item> <!-- 替换为和弹窗背景有对比度的颜色 --> </style>
注意:请优先使用
androidx.appcompat.app.AlertDialog而非原生android.app.AlertDialog,前者的跨版本适配效果更稳定。
内容的提问来源于stack exchange,提问作者Nima Khalili
相关产品推荐
相关产品推荐

