如何更改 AlertDialog 的主题 [英] How to change theme for AlertDialog
问题描述
我想知道是否有人可以帮助我.我正在尝试创建一个自定义的 AlertDialog.为了做到这一点,我在styles.xml
I was wondering if someone could help me out. I am trying to create a custom AlertDialog. In order to do this, I added the following line of code in styles.xml
<resources>
<style name="CustomAlertDialog" parent="android:Theme.Dialog.Alert">
<item name="android:windowBackground">@drawable/color_panel_background</item>
</style>
</resources>
- color_panel_background.9.png 位于 drawable 文件夹中.这也可以在 Android SDK res 文件夹中找到.
以下是主要活动.
package com.customdialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
public class CustomDialog extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTheme(R.style.CustomAlertDialog);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("HELLO!");
builder .setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//dialog.cancel();
}
});
AlertDialog alertdialog = builder.create();
alertdialog.show();
}
}
为了将主题应用于 AlertDialog,我必须将主题设置为当前上下文.
In order to apply the theme to an AlertDialog, I had to set the theme to the current context.
但是,我似乎无法让应用程序显示自定义的 AlertDialog.有人能帮我解决这个问题吗?
However, I just can't seem to get the app to show customized AlertDialog. Can anyone help me out with this?
推荐答案
在 Dialog.java (Android src) 中使用了 ContextThemeWrapper.因此,您可以复制这个想法并执行以下操作:
In Dialog.java (Android src) a ContextThemeWrapper is used. So you could copy the idea and do something like:
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
然后像你想要的那样设计:
And then style it like you want:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AlertDialogCustom" parent="@android:style/Theme.Dialog">
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">10sp</item>
</style>
</resources>
这篇关于如何更改 AlertDialog 的主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!