【发布时间】:2014-11-02 02:44:13
【问题描述】:
在过去的几天里,我阅读了很多关于在 Android 中自定义 AlertDialogs 的问题、答案和解决方案。尽管如此,他们都没有完全帮助我。
所以我的问题是:
通过setSingleChoiceItems 或setItems 将项目添加到AlertDialog 时使用什么布局元素?
注意:我想在代码中设置样式,而不是通过主题/样式解决方案!
至此,我使用了以下答案的组合来实现自定义标题、标题内容分隔符和不同的按钮颜色。
Android - AlertDialog styling
Changing the background drawable of the searchview widget
我的自定义对话框如下所示:
如您所见,我将标题的背景和按钮染成白色,并将标题本身和分隔线染成红色,但没有将这些单选项目的颜色染成红色。
为此,我查看了 android-sources,特别是“alert_dialog_holo.xml”。我发现AlertDialog 是由多个相互嵌套的LinearLayouts 构建的(我从第二个链接中采用了这种方法)。在确定了我想要设置样式的元素后,我使用了 Link 1 的方法(将 onShowListener 定义为 AlertDialog)来更改它们的颜色。这对每个元素都非常有效,无论是标题、分隔线、按钮还是内容(标准文本内容以及自定义内容,例如 DatePicker)。
现在我被困在最后一部分(见上面的问题),因为似乎这些项目没有被加载到“正常”内容的ScrollView 中,也没有加载到自定义内容的FrameLayout 中(我管理以白色背景设置样式)。
那么有人可以指出我在使用 setSingleChoiceItems 或 setItems 方法时使用的布局元素吗?
为了完成,我添加了我如何创建显示的 AlertDialog 的代码,以及我如何设置它的样式:
对话框的创建:
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.currency_choose))
.setCancelable(false)
.setSingleChoiceItems(R.array.currencies, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
currency = getResources().getStringArray(R.array.currencies)[which].substring(0, 1);
}
})
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// doSomething with clicked item
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
dialog.setOnShowListener(new DialogOnShowListener()); // here happens the styling
dialog.show();
对话框的样式(摘录,但应该足以理解):
@Override
public void onShow(DialogInterface dialog) {
Dialog d = ((Dialog) dialog);
int divierId = d.getContext().getResources()
.getIdentifier("android:id/titleDivider", null, null);
View divider = d.findViewById(divierId);
divider.setBackgroundColor(red); // earlier defined color-int
}
在此先感谢,小伙子
【问题讨论】:
-
您是如何将栏标题从蓝色更改为红色的?谢谢。
标签: android android-alertdialog