如何在 Android 上更改 AlertDialog 的主题?

androidmobile developmentapps/applications

Android 中的 AlertDialog 是什么?

Android 中的 AlertDialog 用于在 Android 应用程序中显示警报。我们可以在应用程序中显示 AlertDialog,向用户显示任何警告消息。在 AlertDialog 中,我们可以为用户提供两个选项,在对话框中选择"是"或"否"。在本文中,我们将介绍如何更改 Android 中默认 AlertDialog 的主题。

实现

我们将创建一个简单的应用程序,其中将显示一个简单的文本视图来显示应用程序的标题。之后,我们将显示一个按钮。点击此按钮时,我们将显示一个 AlertDialog,并显示自定义样式的 AlertDialog。

步骤 1:在 Android Studio 中创建新项目

按照以下屏幕所示导航到 Android Studio。在下面的屏幕中,点击"新建项目"以创建一个新的 Android Studio 项目。

点击"新建项目"后,您将看到以下屏幕。

在此屏幕中,我们只需选择"空活动"并点击"下一步"。点击"下一步"后,您将看到以下屏幕。

在此屏幕中,我们只需指定项目名称。然后会自动生成包名。

注意 - 确保选择 Java 作为语言。

完成所有设置后,点击"完成"即可创建一个新的 Android Studio 项目。

项目创建完成后,我们将看到两个打开的文件,即 activity_main.xml 和 MainActivity.java 文件。

步骤 3:使用 activity_main.xml

导航到 activity_main.xml。如果此文件不可见,请在左侧窗格中导航至 app>res>layout>activity_main.xml 以打开此文件。打开此文件后,将以下代码添加到其中。代码中添加了注释,以便您详细了解。

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

说明 - 在上面的代码中,我们创建了一个相对布局作为根布局,并在其中创建了一个文本视图,用于显示应用程序的标题。创建文本视图后,我们将创建一个按钮来打开警报对话框。

最后,我们为相对布局添加一个结束标记。

步骤 4:在 themes.xml 文件中添加自定义样式

由于我们想要更改应用程序内警报对话框的主题,因此我们将在 styles.xml 文件中添加自定义样式。要添加自定义样式,请导航至 app>res>values>themes.xml 文件,并在此文件中添加以下代码。代码中添加了注释,以便您详细了解。

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

步骤 5:使用 MainActivity.java 文件

导航到 MainActivity.java。如果此文件不可见,请打开此文件。在左侧窗格中,导航至 app>res>layout>MainActivity.java 以打开此文件。打开此文件后,将以下代码添加到其中。代码中添加了注释,以便您详细了解。

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 {

   // 在下面的行中,我们正在为按钮创建变量。
   private Button displayAlertDialog;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // 在下面一行使用 id 初始化网页视图。
      displayAlertDialog = findViewById(R.id.idBtnSwitchOff);
      // 在下面的行中添加关闭按钮的点击监听器。
      displayAlertDialog.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {

            // 下面一行我们为构建器创建了一个变量,用于构建我们的警报对话框,并向其传递一个自定义主题。
            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.AlertDialogCustom));
            
            // 下面一行我们设置警报对话框的消息。
            builder.setMessage("Welcome to Tutorials Point");
            
            // 下面一行我们设置警报对话框的标题。
            builder.setTitle("Welcome");
            
            // 下面一行我们设置警报对话框的可取消性。
            builder.setCancelable(false);
            
            // 下面一行我们设置警报对话框的"肯定"按钮,并为其添加点击监听器。
            builder.setPositiveButton("Cancel", (DialogInterface.OnClickListener) (dialog, which) -> {
            
            // 下面的方法用于关闭对话框。
            dialog.cancel();
            });
            
            // 下面一行我们正在创建警报对话框
            AlertDialog alertDialog = builder.create();
            
            // 下面一行我们正在显示警报对话框。
            alertDialog.show();

         }
      });
   }
}

说明 - 在上面的代码中,我们首先为按钮创建变量。在 onCreate 方法中,我们使用在 activity_main.xml 文件中指定的 id 初始化按钮变量。之后,我们为按钮添加了一个点击监听器。在 onclicklistener 中,我们创建了警报对话框并为其设置了自定义主题。之后,我们为警报对话框添加了一个"肯定"按钮,并为其添加了一个点击监听器。最后,我们调用 show 方法来显示警报对话框。

添加上述代码后,只需点击顶部栏中的绿色图标即可在移动设备上运行我们的应用程序。

注意 - 确保您已连接到真实设备或模拟器。

输出

结论

在以上教程中,我们学习了如何为 Android 应用程序创建警报对话框。此外,我们还学习了如何在 Android 应用程序中更改警报对话框的主题。


相关文章