如何改变AlertDialog的主题

我在想有没有人能帮我一下。我试图创建一个自定义AlertDialog。为了做到这一点,我在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位于可绘制文件夹。这也可以在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,我必须将主题设置为当前上下文。

然而,我似乎不能让应用程序显示自定义的AlertDialog。有人能帮我一下吗?

411418 次浏览

我想这是不可能的。至少不是和建造者。我正在使用1.6和Builder.create()中的实现是:

public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext);
P.apply(dialog.mAlert);
[...]
}

它调用AlertDialog的“非主题感知”构造函数,看起来像这样:

protected AlertDialog(Context context) {
this(context, com.android.internal.R.style.Theme_Dialog_Alert);
}

在AlertDialog中有第二个构造函数用于更改主题:

protected AlertDialog(Context context, int theme) {
super(context, theme);
[...]
}

建造者就是不叫。

如果Dialog非常通用,我会试着编写AlertDialog的子类,调用第二个构造函数并使用该类而不是生成器机制。

在Dialog.java (Android src)中使用ContextThemeWrapper。所以你可以复制这个想法,然后做如下的事情:

AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));

然后像你想要的样式:

<?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主题相关的问题使用sdk 1.6如下所述

我通过以下方法解决了这个问题:

  new AlertDialog.Builder(
new ContextThemeWrapper(context, android.R.style.Theme_Dialog))

希望这能有所帮助。

我一直在努力解决这个问题——你可以在你的主题中使用android:alertDialogStyle="@style/AlertDialog"来设置对话框的背景,但它忽略了你所拥有的任何文本设置。正如@rflexor上面所说的,在Honeycomb之前的SDK无法做到这一点(你可以使用Reflection)。

简而言之,我的解决方案是使用上述方法设置对话框的背景样式,然后设置自定义标题和内容视图(使用与SDK中相同的布局)。

我的包装:

import com.mypackage.R;


import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


public class CustomAlertDialogBuilder extends AlertDialog.Builder {


private final Context mContext;
private TextView mTitle;
private ImageView mIcon;
private TextView mMessage;


public CustomAlertDialogBuilder(Context context) {
super(context);
mContext = context;


View customTitle = View.inflate(mContext, R.layout.alert_dialog_title, null);
mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
mIcon = (ImageView) customTitle.findViewById(R.id.icon);
setCustomTitle(customTitle);


View customMessage = View.inflate(mContext, R.layout.alert_dialog_message, null);
mMessage = (TextView) customMessage.findViewById(R.id.message);
setView(customMessage);
}


@Override
public CustomAlertDialogBuilder setTitle(int textResId) {
mTitle.setText(textResId);
return this;
}
@Override
public CustomAlertDialogBuilder setTitle(CharSequence text) {
mTitle.setText(text);
return this;
}


@Override
public CustomAlertDialogBuilder setMessage(int textResId) {
mMessage.setText(textResId);
return this;
}


@Override
public CustomAlertDialogBuilder setMessage(CharSequence text) {
mMessage.setText(text);
return this;
}


@Override
public CustomAlertDialogBuilder setIcon(int drawableResId) {
mIcon.setImageResource(drawableResId);
return this;
}


@Override
public CustomAlertDialogBuilder setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
return this;
}


}

alert_dialog_title.xml(取自SDK)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:id="@+id/title_template"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:layout_marginTop="6dip"
android:layout_marginBottom="9dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip">


<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingTop="6dip"
android:paddingRight="10dip"
android:src="@drawable/ic_dialog_alert" />
<TextView android:id="@+id/alertTitle"
style="@style/?android:attr/textAppearanceLarge"
android:singleLine="true"
android:ellipsize="end"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView android:id="@+id/titleDivider"
android:layout_width="fill_parent"
android:layout_height="1dip"
android:scaleType="fitXY"
android:gravity="fill_horizontal"
android:src="@drawable/divider_horizontal_bright" />
</LinearLayout>

alert_dialog_message.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="2dip"
android:paddingBottom="12dip"
android:paddingLeft="14dip"
android:paddingRight="10dip">
<TextView android:id="@+id/message"
style="?android:attr/textAppearanceMedium"
android:textColor="@color/dark_grey"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5dip" />
</ScrollView>

然后使用CustomAlertDialogBuilder而不是AlertDialog.Builder来创建对话框,并像往常一样调用setTitlesetMessage

它可以通过使用生成器的setView()简单地完成。您可以创建所选择的任何视图,并将其提供给构建器。这很有效。我使用一个自定义的TextView,由对话生成器呈现。我不设置消息和这个空间是用来渲染我的自定义textview。

任何试图在Fragment(使用支持库,即pre API 11)中做到这一点的人都应该这样做:

public class LoadingDialogFragment extends DialogFragment {
public static final String ID = "loadingDialog";


public static LoadingDialogFragment newInstance() {
LoadingDialogFragment f = new LoadingDialogFragment();


return f;
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
StyleAlertDialog adb = new StyleAlertDialog(getActivity(), R.style.Your_Style);
adb.setView(getActivity().getLayoutInflater().inflate(R.layout.fragment_dialog_layout, null));
return adb;
}


private class StyleAlertDialog extends AlertDialog {
protected StyleAlertDialog(Context context, int theme) {
super(context, theme);
}
}
}

@Rflexor鼓励我扩展AlertDialog并公开构造函数

Arve Waltin的解决方案看起来不错,尽管我还没有测试过。还有另一个解决方案,以防你有麻烦,让它工作....扩展AlertDialog.Builder并覆盖所有的方法(例如。setTextsetTitlesetView等)不设置实际的对话框的文本/标题/视图,而是在对话框的视图中创建一个新视图,在那里做所有的事情。然后你就可以随心所欲地设计一切了。

澄清一下,就父类而言,设置的是View,而不是其他。

就您的自定义扩展类而言,一切都在该视图中完成。

我已经在我的博客中写了一个文章关于如何配置AlertDialog的XML样式文件的布局。主要的问题是不同的布局参数需要不同的样式定义。下面是一个基于Holo Light平台19版AlertDialog样式的样板文件,该样式文件应该涵盖一系列标准布局方面,如文本大小和背景颜色。

<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
...
<item name="android:alertDialogTheme">@style/MyAlertDialogTheme</item>
<item name="android:alertDialogStyle">@style/MyAlertDialogStyle</item>
...
</style>


<style name="MyBorderlessButton">
<!-- Set background drawable and text size of the buttons here -->
<item name="android:background">...</item>
<item name="android:textSize">...</item>
</style>


<style name="MyButtonBar">
<!-- Define a background for the button bar and a divider between the buttons here -->
<item name="android:divider">....</item>
<item name="android:dividerPadding">...</item>
<item name="android:showDividers">...</item>
<item name="android:background">...</item>
</style>


<style name="MyAlertDialogTitle">
<item name="android:maxLines">1</item>
<item name="android:scrollHorizontally">true</item>
</style>


<style name="MyAlertTextAppearance">
<!-- Set text size and color of title and message here -->
<item name="android:textSize"> ... </item>
<item name="android:textColor">...</item>
</style>


<style name="MyAlertDialogTheme">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowTitleStyle">@style/MyAlertDialogTitle</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
<item name="android:windowIsFloating">true</item>
<item name="android:textAppearanceMedium">@style/MyAlertTextAppearance</item>
<!-- If you don't want your own button bar style use
@android:style/Holo.Light.ButtonBar.AlertDialog
and
?android:attr/borderlessButtonStyle
instead of @style/MyButtonBar and @style/MyBorderlessButton -->
<item name="android:buttonBarStyle">@style/MyButtonBar</item>
<item name="android:buttonBarButtonStyle">@style/MyBorderlessButton</item>
</style>


<style name="MyAlertDialogStyle">
<!-- Define background colors of title, message, buttons, etc. here -->
<item name="android:fullDark">...</item>
<item name="android:topDark">...</item>
<item name="android:centerDark">...</item>
<item name="android:bottomDark">...</item>
<item name="android:fullBright">...</item>
<item name="android:topBright">...</item>
<item name="android:centerBright">...</item>
<item name="android:bottomBright">...</item>
<item name="android:bottomMedium">...</item>
<item name="android:centerMedium">...</item>
</style>

更好的方法是使用自定义对话框,并根据您的需要定制自定义对话框示例.....

enter image description here

public class CustomDialogUI {
Dialog dialog;
Vibrator vib;
RelativeLayout rl;


@SuppressWarnings("static-access")
public void dialog(final Context context, String title, String message,
final Runnable task) {
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom);
dialog.setCancelable(false);
TextView m = (TextView) dialog.findViewById(R.id.message);
TextView t = (TextView) dialog.findViewById(R.id.title);
final Button n = (Button) dialog.findViewById(R.id.button2);
final Button p = (Button) dialog.findViewById(R.id.next_button);
rl = (RelativeLayout) dialog.findViewById(R.id.rlmain);
t.setText(bold(title));
m.setText(message);
dialog.show();
n.setText(bold("Close"));
p.setText(bold("Ok"));
// color(context,rl);
vib = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
n.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
vib.vibrate(15);
dialog.dismiss();
}
});
p.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
vib.vibrate(20);
dialog.dismiss();
task.run();
}
});
}
//customize text style bold italic....
public SpannableString bold(String s) {
SpannableString spanString = new SpannableString(s);
spanString.setSpan(new StyleSpan(Typeface.BOLD), 0,
spanString.length(), 0);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
// spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0,
// spanString.length(), 0);
return spanString;
}

这是xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
>


<RelativeLayout
android:id="@+id/rlmain"
android:layout_width="fill_parent"
android:layout_height="150dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="#569CE3" >


<RelativeLayout
android:id="@+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="25dip"
android:layout_marginTop="10dip" >


<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Are you Sure?"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff"
android:textSize="13dip" />
</RelativeLayout>


<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/relativeLayout1"
android:layout_alignRight="@+id/relativeLayout1"
android:layout_below="@+id/relativeLayout1"
android:layout_marginTop="5dip" >
</RelativeLayout>


<ProgressBar
android:id="@+id/process"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="3dip"
android:layout_marginTop="3dip" />


<RelativeLayout
android:id="@+id/relativeLayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/relativeLayout2"
android:layout_below="@+id/relativeLayout2"
android:layout_toLeftOf="@+id/process" >


<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff"
android:textSize="13dip"/>


</RelativeLayout>


<Button
android:id="@+id/next_button"
android:layout_width="90dip"
android:layout_height="35dip"
android:layout_alignParentBottom="true"
android:textColor="@drawable/button_text_color"
android:background="@drawable/blue_button"
android:layout_marginBottom="5dp"
android:textSize="10dp"


android:layout_alignRight="@+id/relativeLayout3"
android:text="Okay" />


<Button
android:id="@+id/button2"
android:text="Cancel"
android:textColor="@drawable/button_text_color"
android:layout_width="90dip"
android:layout_height="35dip"
android:layout_marginBottom="5dp"
android:background="@drawable/blue_button"
android:layout_marginRight="7dp"
android:textSize="10dp"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/next_button"
/>


</RelativeLayout>

 <style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">@color/colorAccent</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">#FFFFFF</item>
<!-- Used for the background -->
<item name="android:background">@color/teal</item>
</style>










new AlertDialog.Builder(new ContextThemeWrapper(context,R.style.AlertDialogCustom))
.setMessage(Html.fromHtml(Msg))
.setPositiveButton(posBtn, okListener)
.setNegativeButton(negBtn, null)
.create()
.show();

自定义对话框:

在对话框构造函数中调用super(context,R.style.<dialog style>)而不是super(context)

public class MyDialog extends Dialog
{
public MyDialog(Context context)
{
super(context, R.style.Theme_AppCompat_Light_Dialog_Alert)
}
}
< p > < br > AlertDialog: < / >强

用这个构造函数创建alertDialog:

 new AlertDialog.Builder(
new ContextThemeWrapper(context, android.R.style.Theme_Dialog))

当你初始化Builder时,你可以直接分配一个主题:

AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity(), R.style.MyAlertDialogTheme);

然后在values/styles.xml中自定义主题

<!-- Alert Dialog -->
<style name="MyAlertDialogTheme" parent="Theme.AppCompat.Dialog.Alert">
<item name="colorAccent">@color/colorAccent</item>
<item name="android:colorBackground">@color/alertDialogBackground</item>
<item name="android:windowBackground">@color/alertDialogBackground</item>
</style>
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
builder.setMessage("Description");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

我不确定Arve的解决方案如何在自定义对话框中工作,其中视图通过LayoutInflator膨胀。

解决方案应该是通过cloneInContext()在inflator中插入ContextThemeWrapper:

View sensorView = LayoutInflater.from(context).cloneInContext(
new ContextThemeWrapper(context, R.style.AppTheme_DialogLight)
).inflate(R.layout.dialog_fingerprint, null);

您可以通过修改活动的主题属性....来覆盖由活动生成的DialogFragments所使用的默认主题

AndroidManifest.xml中设置活动的主题。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld">


<application
android:name=".App"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">     <!-- set all Activity themes to your custom theme -->


.....


</application>


</manifest>

values/styles.xml中,重写用于确定派生的DialogFragments使用什么主题的项

<?xml version="1.0" encoding="utf-8"?>
<resources>


<style name="AppTheme" parent="Theme.AppCompat">


<!-- override the default theme for DialogFragments -->
<item name="android:dialogTheme">@style/AppTheme.Dialog</item>


</style>


.....


</resources>

values/styles.xml中,定义并配置你想要用于DialogFragments的主题

<?xml version="1.0" encoding="utf-8"?>
<resources>


.....


<!--
configure your custom theme for DialogFragments...
-->
<style name="AppTheme.Dialog" parent="Theme.AppCompat.Dialog.MinWidth">


<!-- override the default theme for DialogFragments spawned by this DialogFragment -->
<item name="android:dialogTheme">@style/AppTheme.Dialog</item>


<!--
OPTIONAL: override the background for the dialog...i am using a dark theme,
and for some reason, there is no themes for dialogs with dark backgrounds,
so, i made my own.
-->
<item name="android:windowBackground">@drawable/dialog__window_background</item>


<!--
add the title to the dialog's theme. you can remove it later by using
DialogFragment.setStyle()
-->
<item name="android:windowNoTitle">false</item>
<item name="windowNoTitle">?android:windowNoTitle</item>


</style>


.....


</resources>

可选:如果你使用黑色主题,并像我在AppTheme.Dialog中所做的那样覆盖android:windowBackground,然后添加一个包含以下内容的drawable/dialog__window_background.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="16dp"
android:insetTop="16dp"
android:insetRight="16dp"
android:insetBottom="16dp">
<shape android:shape="rectangle">
<corners android:radius="?dialogCornerRadius" />
<solid android:color="?android:colorBackground" />
</shape>
</inset>