使用 Kotlin 创建 Android 警报对话框

在本教程中,我们将讨论警报对话框并使用Kotlin在我们的Android应用程序中实现它们。

警报对话框

警报对话框是屏幕上弹出的窗口。它们通常会显示一些信息,并要求用户执行操作。有三个构建警报对话框的核心组件。

  • 标题文本
  • 消息文本
  • 按钮-有三种类型的按钮:正按钮、负按钮和中性按钮

要创建一个AlertDialog,我们使用AlertDialog.Builder内部类。

1val alertDialogBuilder = AlertDialog.Builder(this)

我们将上下文传递到构造函数中。或者,我们可以传递另一个参数,即警告对话框样式。

预警对话框方法

可以在AlertDialog上使用的一些方法。

  • setTitle
  • setMessage
  • SETIcon
  • setCustomTitle-在这里,您可以传递一个自定义视图,该视图将取代警报对话框中的标题部分。
  • setPositiveButton-我们传递字符串名称,以及在此处单击的回调方法Button。
  • setView-用于在警报对话框中添加自定义视图。
  • setlist-用于设置将以列表形式显示的字符串数组。
  • setMultiChoiceList-再次我们可以设置数组,但这一次我们可以从列表中选择多个项目,这要归功于复选框。
  • setPositiveButtonIcon-在按钮旁边设置一个图标
  • show()-用于显示AlertDialog
  • setDismissListener-在其中,您可以设置在解除警报对话框时触发的逻辑。
  • setShowListener-设置告警对话框解除时触发的逻辑。
  • setCancelable-需要布尔值。默认情况下,所有警告对话框都可以通过点击按钮或触摸外部来取消。如果此方法设置为False,则需要使用Dialog.ancel()方法显式取消该对话框。

预警对话框Kotlin代码

要在Android Studio项目中使用AlertDialog,请导入以下类。

1import android.support.v7.app.AlertDialog;

下面的Kotlin代码用于创建一个简单的警告对话框。

 1val builder = AlertDialog.Builder(this)
 2builder.setTitle("Androidly Alert")
 3builder.setMessage("We have a message")
 4//builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = x))
 5
 6builder.setPositiveButton(android.R.string.yes) { dialog, which ->
 7    Toast.makeText(applicationContext,
 8            android.R.string.yes, Toast.LENGTH_SHORT).show()
 9}
10
11builder.setNegativeButton(android.R.string.no) { dialog, which ->
12    Toast.makeText(applicationContext,
13            android.R.string.no, Toast.LENGTH_SHORT).show()
14}
15
16builder.setNeutralButton("Maybe") { dialog, which ->
17    Toast.makeText(applicationContext,
18            "Maybe", Toast.LENGTH_SHORT).show()
19}
20builder.show()

Builder.show()在屏幕上显示报警对话框。在setPositiveButton函数中,我们传递Button文本和一个Kotlin函数,该函数在按钮被单击时触发。该函数是DialogInterface.OnClickListener()接口的一部分。函数类型为(DialogInterface,Int)->Unit。DialogInterface是Dialog的一个实例,Int是所单击的按钮的id。在上面的代码中,我们将该函数表示为高阶kotlin function.DialogWhich代表两个参数。如果不使用参数,我们可以通过传递_来改进函数。这些函数如下所示:

1builder.setPositiveButton(android.R.string.yes) { _,_ ->
2            Toast.makeText(applicationContext,
3                    android.R.string.yes, Toast.LENGTH_SHORT).show()
4        }

或者,我们也可以通过AlertDialog类实例显示该对话框。将Builder.show()替换为:

1val alertDialog = builder.create()
2alertDialog.show()

我们也可以分别定义更高阶的函数,而不是为每个按钮定义按钮点击侦听器函数。

1val positiveButtonClick = { dialog: DialogInterface, which: Int ->
2    Toast.makeText(applicationContext,
3            android.R.string.no, Toast.LENGTH_SHORT).show()
4}

现在在setPositiveButton Kotlin函数中设置这个val属性:

1builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
2//or
3builder.setPositiveButton(android.R.string.yes, positiveButtonClick)

后者使代码看起来非常简洁。下面是我们的Activity类的屏幕截图,上面的函数应用于每个按钮。安卓基本警报对话框kotlin code

如果您不想在按钮点击上保留任何操作,则可以传递一个空值而不是函数。

Kotlin仍然有更大的能力来提高上面代码的可读性。

简单警报对话框kotlin代码

使用`with‘函数,我们可以增强Kotlin代码的可读性,以创建一个警报对话框。

 1fun basicAlert(view: View){
 2
 3        val builder = AlertDialog.Builder(this)
 4
 5        with(builder)
 6        {
 7            setTitle("Androidly Alert")
 8            setMessage("We have a message")
 9            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
10            setNegativeButton(android.R.string.no, negativeButtonClick)
11            setNeutralButton("Maybe", neutralButtonClick)
12            show()    
13        }
14
15    }

在下一节中,我们将创建Android应用程序,在其中我们将在AlertDialog中实现以下功能。

  • 简单的警报对话框
  • 带有图标和按钮定制的警报对话框
  • 带有列表的警报对话框
  • 带有多项选择列表的警报对话框
  • 带有样式的警报对话框
  • 带自定义样式的警报对话框
  • 带有EditText的警报对话框

Android Studio项目结构

Android Basic提醒对话框项目structure

1.XML布局代码

Activity_main.xml布局的代码如下所示。

 1<?xml version="1.0" encoding="utf-8"?>
 2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3    xmlns:tools="http://schemas.android.com/tools"
 4    android:layout_width="match_parent"
 5    android:layout_height="match_parent"
 6    android:gravity="center"
 7    android:orientation="vertical"
 8    tools:context=".MainActivity">
 9
10    <Button
11        android:id="@+id/btnBasicAlert"
12        android:layout_width="wrap_content"
13        android:onClick="basicAlert"
14        android:layout_height="wrap_content"
15        android:text="BASIC ALERT DIALOG" />
16
17    <Button
18        android:id="@+id/btnAlertWithIconsAndCustomize"
19        android:layout_width="wrap_content"
20        android:onClick="withIconAndCustomise"
21        android:layout_height="wrap_content"
22        android:text="WITH ICON AND CUSTOMIZATION" />
23
24    <Button
25        android:id="@+id/btnAlertWithItems"
26        android:layout_width="wrap_content"
27        android:layout_height="wrap_content"
28        android:onClick="withItems"
29        android:text="WITH ITEMS" />
30
31    <Button
32        android:id="@+id/btnAlertWithMultiChoiceList"
33        android:layout_width="wrap_content"
34        android:layout_height="wrap_content"
35        android:onClick="withMultiChoiceList"
36        android:text="WITH MULTI CHOICE LIST" />
37
38    <Button
39        android:id="@+id/btnAlertWithStyle"
40        android:layout_width="wrap_content"
41        android:layout_height="wrap_content"
42        android:onClick="withStyle"
43        android:text="WITH STYLE" />
44
45    <Button
46        android:id="@+id/btnAlertWithCustomStyle"
47        android:layout_width="wrap_content"
48        android:layout_height="wrap_content"
49        android:onClick="withCustomStyle"
50        android:text="WITH CUSTOM STYLE" />
51
52    <Button
53        android:id="@+id/btnAlertWithButtonCentered"
54        android:layout_width="wrap_content"
55        android:layout_height="wrap_content"
56        android:onClick="withButtonCentered"
57        android:text="WITH BUTTON CENTERED" />
58
59    <Button
60        android:id="@+id/btnAlertWithEditText"
61        android:layout_width="wrap_content"
62        android:layout_height="wrap_content"
63        android:onClick="withEditText"
64        android:text="WITH EDIT TEXT" />
65
66</LinearLayout>

对于每个按钮,我们使用函数名设置了一个android:onClick属性。这些Kotlin函数将在MainActivity.kt类中触发。我们将逐一讨论它们。

2.Kotlin主要活动代码

我们已经在上面创建了第一个警报对话框。让我们来看看MainActivity.kt在使用它时是什么样子。

 1package net.androidly.androidlyalertdialog
 2
 3import android.content.DialogInterface
 4import android.support.v7.app.AppCompatActivity
 5import android.os.Bundle
 6import android.support.v7.app.AlertDialog
 7import android.view.View
 8import android.widget.Toast
 9
10class MainActivity : AppCompatActivity() {
11
12    val positiveButtonClick = { dialog: DialogInterface, which: Int ->
13        Toast.makeText(applicationContext,
14                android.R.string.yes, Toast.LENGTH_SHORT).show()
15    }
16    val negativeButtonClick = { dialog: DialogInterface, which: Int ->
17        Toast.makeText(applicationContext,
18                android.R.string.no, Toast.LENGTH_SHORT).show()
19    }
20    val neutralButtonClick = { dialog: DialogInterface, which: Int ->
21        Toast.makeText(applicationContext,
22                "Maybe", Toast.LENGTH_SHORT).show()
23    }
24
25    override fun onCreate(savedInstanceState: Bundle?) {
26        super.onCreate(savedInstanceState)
27        setContentView(R.layout.activity_main)
28    }
29
30    fun basicAlert(view: View){
31
32        val builder = AlertDialog.Builder(this)
33
34        with(builder)
35        {
36            setTitle("Androidly Alert")
37            setMessage("We have a message")
38            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
39            setNegativeButton(android.R.string.no, negativeButtonClick)
40            setNeutralButton("Maybe", neutralButtonClick)
41            show()
42        }
43
44    }
45}

3.带图标和自定义的提醒对话框

 1val builder = AlertDialog.Builder(this)
 2        with(builder) {
 3            setTitle("Icon and Button Color")
 4            setMessage("We have a message")
 5            setPositiveButton("OK", null)
 6            setNegativeButton("CANCEL", null)
 7            setNeutralButton("NEUTRAL", null)
 8            setPositiveButtonIcon(resources.getDrawable(android.R.drawable.ic_menu_call, theme))
 9            setIcon(resources.getDrawable(android.R.drawable.ic_dialog_alert, theme))
10        }
11        val alertDialog = builder.create()
12        alertDialog.show()
13
14        val button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
15        with(button) {
16            setBackgroundColor(Color.BLACK)
17            setPadding(0, 0, 20, 0)
18            setTextColor(Color.WHITE)
19        }

使用getButton,我们可以通过设置相应的常量来检索任何按钮。一旦检索到按钮,我们就可以如上所述对其进行定制。

4.带条目的告警对话框

 1fun withItems(view: View) {
 2
 3        val items = arrayOf("Red", "Orange", "Yellow", "Blue")
 4        val builder = AlertDialog.Builder(this)
 5        with(builder)
 6        {
 7            setTitle("List of Items")
 8            setItems(items) { dialog, which ->
 9                Toast.makeText(applicationContext, items[which] + " is clicked", Toast.LENGTH_SHORT).show()
10            }
11
12            setPositiveButton("OK", positiveButtonClick)
13            show()
14        }
15    }

在setItems内部,我们传递Kotlin数组。Which参数表示在列表中点击的元素的索引。

5.多选列表告警对话框

 1fun withMultiChoiceList(view: View) {
 2
 3        val items = arrayOf("Microsoft", "Apple", "Amazon", "Google")
 4        val selectedList = ArrayList<Int>()
 5        val builder = AlertDialog.Builder(this)
 6
 7        builder.setTitle("This is list choice dialog box")
 8        builder.setMultiChoiceItems(items, null
 9        ) { dialog, which, isChecked ->
10            if (isChecked) {
11                selectedList.add(which)
12            } else if (selectedList.contains(which)) {
13                selectedList.remove(Integer.valueOf(which))
14            }
15        }
16
17        builder.setPositiveButton("DONE") { dialogInterface, i ->
18            val selectedStrings = ArrayList<string>()
19
20            for (j in selectedList.indices) {
21                selectedStrings.add(items[selectedList[j]])
22            }
23
24            Toast.makeText(applicationContext, "Items selected are: " + Arrays.toString(selectedStrings.toTypedArray()), Toast.LENGTH_SHORT).show()
25        }
26
27        builder.show()
28
29    }

在上面的代码中,我们将选择保存在整数数组列表中,并再次检索它们以在Toast消息中显示它们。

6.有风格的提醒对话框

 1fun withStyle(view: View) {
 2
 3        val builder = AlertDialog.Builder(ContextThemeWrapper(this, android.R.style.Holo_SegmentedButton))
 4
 5        with(builder)
 6        {
 7            setTitle("Androidly Alert")
 8            setMessage("We have a message")
 9            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
10            setNegativeButton(android.R.string.no, negativeButtonClick)
11            setNeutralButton("Maybe", neutralButtonClick)
12            show()
13        }
14    }

如果不使用ConextThemeWrapper,警报对话框将显示在全屏上。

7.自定义样式告警对话框

在styles.xml文件中添加以下代码:

1<style name="AlertDialogCustom" parent="@android:style/Theme.Material.Dialog">
2        <item name="android:textColor">@android:color/white</item>
3        <item name="android:textStyle">bold</item>
4        <item name="android:headerDividersEnabled">true</item>
5        <item name="android:background">@android:color/holo_blue_dark</item>
6    </style>

以下是Kotlin函数:

 1fun withCustomStyle(view: View) {
 2
 3        val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.AlertDialogCustom))
 4
 5        with(builder)
 6        {
 7            setTitle("Androidly Alert")
 8            setMessage("We have a message")
 9            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
10            setNegativeButton(android.R.string.no, negativeButtonClick)
11            setNeutralButton("Maybe", neutralButtonClick)
12            show()
13        }
14
15    }

8.按钮居中的告警对话框

 1fun withButtonCentered(view: View) {
 2
 3        val alertDialog = AlertDialog.Builder(this).create()
 4        alertDialog.setTitle("Title")
 5        alertDialog.setMessage("Message")
 6
 7        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes"
 8        ) { dialog, which -> dialog.dismiss() }
 9
10        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No"
11        ) { dialog, which -> dialog.dismiss() }
12        alertDialog.show()
13
14        val btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
15        val btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
16
17        val layoutParams = btnPositive.layoutParams as LinearLayout.LayoutParams
18        layoutParams.weight = 10f
19        btnPositive.layoutParams = layoutParams
20        btnNegative.layoutParams = layoutParams
21    }

9.带有编辑文本的警报对话框

自定义布局alert_dialog_with_edittext. xml的代码如下所示:

 1<?xml version="1.0" encoding="utf-8"?>
 2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3    android:orientation="vertical"
 4    android:layout_width="match_parent"
 5    android:layout_height="match_parent">
 6
 7    <EditText
 8        android:id="@+id/editText"
 9        android:layout_width="match_parent"
10        android:layout_height="wrap_content"
11        android:hint="Enter the text here"/>
12
13</LinearLayout>
 1fun withEditText(view: View) {
 2        val builder = AlertDialog.Builder(this)
 3        val inflater = layoutInflater
 4        builder.setTitle("With EditText")
 5        val dialogLayout = inflater.inflate(R.layout.alert_dialog_with_edittext, null)
 6        val editText  = dialogLayout.findViewById<EditText>(R.id.editText)
 7        builder.setView(dialogLayout)
 8        builder.setPositiveButton("OK") { dialogInterface, i -> Toast.makeText(applicationContext, "EditText is " + editText.text.toString(), Toast.LENGTH_SHORT).show() }
 9        builder.show()
10    }

上述应用程序的输出如下所示:Android警报对话框演示输出

下载Android Studio项目:AndroidlyAlertDialog

Published At
Categories with 技术
Tagged with
comments powered by Disqus