正常声明一个单选列表弹窗,如下代码:
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AlertDialog_Base);
String []items = {"1111111","2222222","3333333","4444444","5555555"
,"6666666","7777777","8888888","9999999","0000000","1111111","2222222","3333333","4444444","5555555"
,"6666666","7777777","8888888","9999999","0000000","1111111","2222222","3333333","4444444","5555555"};
AlertDialog alertDialog = builder.setTitle("设置")
.setSingleChoiceItems(items,0,null)
.setPositiveButton("ok", null)
.create();
alertDialog.show();
其中style的声明只添加一个圆角属性:
<style name="Theme.AlertDialog.Base" parent="@style/Theme.AppCompat.DayNight.Dialog.Alert">
<item name="dialogCornerRadius">12dp</item>
</style>
效果图如下:
自定义列表弹窗的单选图标样式:
在style中对Theme_AlertDialog_Base添加声明定义选中和未选中状态的drawable的selector类型文件:
<item name="android:listChoiceIndicatorSingle">@drawable/selector_ok_bg_enable</item>
去掉列表弹窗的上下提示线:
可以看到列表过长的时候,在列表底部是有提示线的,滑动下来的时候,顶部也会有提示线提示可以上往上滑动。有需求要求去掉这个原生自带的提示线行为,我们追踪源码可以看到提示线是在这个地方声明添加的:
那么,我们只需要在dialog show出来之后去设置这个setScrollIndicators为0即可:
AlertDialog alertDialog = builder.setTitle("设置")
.setSingleChoiceItems(items,0,null)
.setPositiveButton("ok", null)
.create();
alertDialog.setOnShowListener(dialog -> {
alertDialog.getListView().setScrollIndicators(0);
});
alertDialog.show();
效果如图:
OK按钮的颜色:
比较简单的方式是直接在style中对Theme_AlertDialog_Base添加属性声明:
<item name="android:colorAccent">@color/blue</item> <!--按钮颜色-->
如果需要复杂一点的样式,则声明确认按钮的style:
<item name="buttonBarPositiveButtonStyle">@style/BtnOk</item>
而BtnOk的声明方式格式如下:
<style name="BtnOk" parent="TextAppearance.AppCompat.Widget.Button">
<item name="android:background">@drawable/test_shape</item>
<item name="android:textColor">@color/white</item>
</style>