📌  相关文章
📜  Android 中带有 SingleItemSelection 的警报对话框

📅  最后修改于: 2022-05-13 01:54:31.439000             🧑  作者: Mango

Android 中带有 SingleItemSelection 的警报对话框

警报对话框是用户对应用程序执行一些关键操作时弹出的 UI 元素。这些类似于窗口的元素可能包含多个或单个项目以从列表中选择,或者可能包含错误消息和一些操作按钮。在本文中,讨论了如何使用单项选择实现警报对话框。查看下图以区分带有操作按钮和单个项目选择的警报对话框。请注意,我们将使用Java语言来实现这个项目。

Android 中带有 SingleItemSelection 的警报对话框

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!

使用单项选择实现警报对话框的步骤

第 1 步:创建一个空的 Activity Android Studio 项目

  • 创建一个空的活动 Android Studio 项目。并选择Java作为编程语言。
  • 参考安卓 |如何在 Android Studio 中创建/启动新项目?了解如何创建一个空的活动 Android Studio 项目。

步骤 2:使用 activty_main.xml 文件

  • 在包含一个按钮和 TextView 的 activity_main.xml 中。用于打开带有单个项目选择列表的警报对话框的按钮。以及预览所选项目的文本视图,该项目由用户选择。
  • 在activity_main.xml 文件中调用以下布局代码,该文件仅包含一个Button 和TextView 元素。
XML


  
    


Java
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
  
public class MainActivity extends AppCompatActivity {
  
    // Button and TextView instances
    Button bOpenAlertDialog;
    TextView tvSelectedItemPreview;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register both UI elements with their appropriate IDs.
        bOpenAlertDialog = findViewById(R.id.openAlertDialogButton);
        tvSelectedItemPreview = findViewById(R.id.selectedItemPreview);
  
        // single item array instance to store 
          // which element is selected by user
        // initially it should be set to zero meaning 
          // none of the element is selected by default
        final int[] checkedItem = {-1};
  
        // handle the button to open the alert dialog with
          // the single item selection when clicked
        bOpenAlertDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
  
                // AlertDialog builder instance to build the alert dialog
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
  
                // set the custom icon to the alert dialog
                alertDialog.setIcon(R.drawable.image_logo);
  
                // title of the alert dialog
                alertDialog.setTitle("Choose an Item");
  
                // list of the items to be displayed to 
                  // the user in the form of list
                // so that user can select the item from
                final String[] listItems = new String[]{"Android Development", "Web Development", "Machine Learning"};
  
                // the function setSingleChoiceItems is the function which builds
                // the alert dialog with the single item selection
                alertDialog.setSingleChoiceItems(listItems, checkedItem[0], new DialogInterface.OnClickListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
  
                        // update the selected item which is selected by the user
                        // so that it should be selected when user opens the dialog next time
                        // and pass the instance to setSingleChoiceItems method
                        checkedItem[0] = which;
  
                        // now also update the TextView which previews the selected item
                        tvSelectedItemPreview.setText("Selected Item is : " + listItems[which]);
  
                        // when selected an item the dialog should be closed with the dismiss method
                        dialog.dismiss();
                    }
                });
  
                // set the negative button if the user 
                  // is not interested to select or change
                // already selected item
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
  
                    }
                });
  
                // create and build the AlertDialog instance 
                  // with the AlertDialog builder instance
                AlertDialog customAlertDialog = alertDialog.create();
  
                // show the alert dialog when the button is clicked
                customAlertDialog.show();
            }
        });
    }
}


输出界面:

Android 中带有 SingleItemSelection 的警报对话框

第 3 步:使用 MainActivity。 Java文件

  • 需要了解单项选择的 AlertDialog 的各个部分。看看下面的图片:

Android 中带有 SingleItemSelection 的警报对话框

  • 用于实现单项选择的函数是setSingleChoiceItems ,将在下面讨论:
  • 调用以下代码。代码中添加了注释以便更好地理解。

Java

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
  
public class MainActivity extends AppCompatActivity {
  
    // Button and TextView instances
    Button bOpenAlertDialog;
    TextView tvSelectedItemPreview;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register both UI elements with their appropriate IDs.
        bOpenAlertDialog = findViewById(R.id.openAlertDialogButton);
        tvSelectedItemPreview = findViewById(R.id.selectedItemPreview);
  
        // single item array instance to store 
          // which element is selected by user
        // initially it should be set to zero meaning 
          // none of the element is selected by default
        final int[] checkedItem = {-1};
  
        // handle the button to open the alert dialog with
          // the single item selection when clicked
        bOpenAlertDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
  
                // AlertDialog builder instance to build the alert dialog
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
  
                // set the custom icon to the alert dialog
                alertDialog.setIcon(R.drawable.image_logo);
  
                // title of the alert dialog
                alertDialog.setTitle("Choose an Item");
  
                // list of the items to be displayed to 
                  // the user in the form of list
                // so that user can select the item from
                final String[] listItems = new String[]{"Android Development", "Web Development", "Machine Learning"};
  
                // the function setSingleChoiceItems is the function which builds
                // the alert dialog with the single item selection
                alertDialog.setSingleChoiceItems(listItems, checkedItem[0], new DialogInterface.OnClickListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
  
                        // update the selected item which is selected by the user
                        // so that it should be selected when user opens the dialog next time
                        // and pass the instance to setSingleChoiceItems method
                        checkedItem[0] = which;
  
                        // now also update the TextView which previews the selected item
                        tvSelectedItemPreview.setText("Selected Item is : " + listItems[which]);
  
                        // when selected an item the dialog should be closed with the dismiss method
                        dialog.dismiss();
                    }
                });
  
                // set the negative button if the user 
                  // is not interested to select or change
                // already selected item
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
  
                    }
                });
  
                // create and build the AlertDialog instance 
                  // with the AlertDialog builder instance
                AlertDialog customAlertDialog = alertDialog.create();
  
                // show the alert dialog when the button is clicked
                customAlertDialog.show();
            }
        });
    }
}

输出:在模拟器上运行