How to change theme for AlertDialog on Android?


What is Alert Dialog in Android?

Alert dialogs in android are used to display alerts within android applications. We can display alert dialog within our application to display any warning message to the user. Inside the alert dialog we can provide two options to the users whether to select as yes or no in the dialog. In this article we will take a look on How to change the theme for default Alert Dialog in Android.

Implementation

We will be creating a simple application in which we will be displaying a simple text view for displaying the heading of our application. After that we will be displaying a button. We will be displaying an alert dialog on click of this button and displaying the custom styled alert dialog.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 3 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Custom Styled Alert Dialog"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- creating a button to display alert dialog-->
   <Button
      android:id="@+id/idBtnSwitchOff"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@id/idTVHeading"
      android:layout_centerInParent="true"
      android:layout_margin="10dp"
      android:text="Display Alert Dialog"
      android:textAllCaps="false" />
</RelativeLayout>

Explanation − In the above code we are creating a Relative layout as a root layout and inside that we are creating a text view which we will be using to display the heading of our application. After creating a text view we will be creating a button to open our alert dialog.

Lastly we are adding a closing tag for our Relative Layout.

Step 4 : Adding a custom style in themes.xml file

As we want to change the theme for our Alert Dialog Box inside our application, we will be adding a custom style inside our styles.xml file. For adding a custom style. Navigate to app>res>values>themes.xml file and inside this file. Add below code to it. Comments are added in the code to get to know in detail.

<resources xmlns:tools="http://schemas.android.com/tools">
   <!-- Base application theme. -->
   <style name="Theme.AndroidJAVAApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
       <!-- Primary brand color. -->
       <item name="colorPrimary">@color/purple_500</item>
       <item name="colorPrimaryVariant">@color/purple_700</item>
       <item name="colorOnPrimary">@color/white</item>
       <!-- Secondary brand color. -->
       <item name="colorSecondary">@color/teal_200</item>
       <item name="colorSecondaryVariant">@color/teal_700</item>
       <item name="colorOnSecondary">@color/black</item>
       <!-- Status bar color. -->
       <item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
       <!-- Customize your theme here. -->
   </style>

   <!-- on below line creating a theme for our Alert Dialog -->
   <style name="AlertDialogCustom" parent="@style/MaterialAlertDialog.Material3">
       <!-- on below line adding text color for our text in alert dialog -->
       <item name="android:textColor">@color/black</item>
       <!-- on below line adding typeface for alert dialog text -->
       <item name="android:typeface">monospace</item>
       <!-- on below line setting text size for text -->
       <item name="android:textSize">20sp</item>
   </style>
</resources>

Step 5 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.androidjavaapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ContextThemeWrapper;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

   // on below line we are creating variable for button.
   private Button displayAlertDialog;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // on below line initializing web view with id.
      displayAlertDialog = findViewById(R.id.idBtnSwitchOff);
      // on below line adding click listener for our switch off button.
      displayAlertDialog.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {

            // on below line we are creating a variable for builder to build our alert dialog and passing a custom theme to it.
            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.AlertDialogCustom));

            // on below line we are setting message for our alert dialog.
            builder.setMessage("Welcome to Tutorials Point");

            // on below line we are setting title for our alert dialog.
            builder.setTitle("Welcome");

            // on below line we are setting cancelable for our alert dialog.
            builder.setCancelable(false);

            // on below line we are setting positive button for our alert dialog and adding click listener to it.
            builder.setPositiveButton("Cancel", (DialogInterface.OnClickListener) (dialog, which) -> {
               
               // below method is use to dismiss the dialog.
               dialog.cancel();
            });

            // on below line we are Creating the Alert dialog
            AlertDialog alertDialog = builder.create();
            
            // on below line we are displaying our alert dialog.
            alertDialog.show();

         }
      });
   }
}

Explanation − In the above code firstly we are creating variables for our button. Inside the onCreate method we are initializing the button variable with the id which we have given in our activity_main.xml file. After that we are adding a click listener for our button.Inside onclicklistener for our button. We are creating our alert dialog and setting a custom theme to it. After that we are adding a positive button for our alert dialog and we are adding a click listener for that as well. Lastly we are calling the show method to display our alert dialog.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above tutorial we have taken a look on How to create an Alert Dialog for your android application. Along with that we also get to learn on How to change the theme for Alertdialog inside your android application.

Updated on: 30-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements