How do I change the theme of AlertDialog?

Asked 2 years ago, Updated 2 years ago, 120 views

You are about to create a custom AlertDialog. I added the code below to styles.xml.

Put
color_panel_background9.png in the drawable folder. It's also in the res folder of the Android SDK. 

From mainActivity

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();
    }
}

I set a theme in the current context and applied the theme to AlertDialog Custom AlertDialog doesn't come out in the app. What should I do?

android themes alert dialog

2022-09-22 21:36

1 Answers

Dialog.Use Context ThemeWrapper in java.

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

Like this. And the style is

<?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>

Please specify the style you want in this way.


2022-09-22 21:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.