使用Kotlin编写的Android警示对话框

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

警报对话框

警示对话框是弹出在屏幕上的窗口。它们通常显示一些信息并要求用户采取某种操作。构成警示对话框的核心组件有三个。

  • Title Text
  • Message Text
  • Buttons – There are three types of buttons: Positive, Negative, and Neutral

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

val alertDialogBuilder = AlertDialog.Builder(this)

我们在构造函数中传递上下文。可选的是,我们可以传递另一个参数,即警示对话框的样式。

提示对话框的方法

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

  • setTitle
  • setMessage
  • setIcon
  • setCustomTitle – Here you can pass a custom view that’ll be put in place of the title part in the alert dialog.
  • setPositiveButton – We pass the string name, as well as Button, clicked callback method here.
  • setView – used to add a custom view inside the alert dialog.
  • setList – used to set an array of strings which would be displayed in the form of a List.
  • setMultiChoiceList – again we can set an array but this time we can select multiple items from the List thanks to CheckBox.
  • setPositiveButtonIcon – set an icon alongside the Button
  • show() – used to display the AlertDialog
  • setDismissListener – Inside this, you can set the logic to be triggered when the alert dialog is dismissed.
  • setShowListener – set the logic to be triggered when the alert dialog is dismissed.
  • setCancelable – requires a boolean value. By default all alert dialogs are cancelable on button click or touch outside. If this method is set to false, you need to explicitly cancel the dialog using dialog.cancel() method.

弹出对话框的 Kotlin 代码

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

import android.support.v7.app.AlertDialog;

以下的Kotlin代码用于创建一个简单的提示对话框。

val builder = AlertDialog.Builder(this)
builder.setTitle("Androidly Alert")
builder.setMessage("We have a message")
//builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = x))

builder.setPositiveButton(android.R.string.yes) { dialog, which ->
    Toast.makeText(applicationContext,
            android.R.string.yes, Toast.LENGTH_SHORT).show()
}
        
builder.setNegativeButton(android.R.string.no) { dialog, which ->
    Toast.makeText(applicationContext,
            android.R.string.no, Toast.LENGTH_SHORT).show()
}

builder.setNeutralButton("Maybe") { dialog, which ->
    Toast.makeText(applicationContext,
            "Maybe", Toast.LENGTH_SHORT).show()
}
builder.show()

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

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

另外,我们也可以通过AlertDialog类的实例展示对话框。将builder.show()替换为:

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

与其为每个按钮都定义按钮点击监听器函数,我们也可以将高阶函数分别定义。

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

现在将这个`val`属性设置到`setPositiveButton`的Kotlin函数内部:

builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
//or
builder.setPositiveButton(android.R.string.yes, positiveButtonClick)
android basic alert dialog kotlin code

如果你不打算在按钮点击时执行任何操作,你可以传递一个空值代替该函数。

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

Kotlin代码的简单警报对话框。

通过使用with函数,我们可以提高Kotlin代码创建警示对话框的可读性。

fun basicAlert(view: View){

        val builder = AlertDialog.Builder(this)
        
        with(builder)
        {
            setTitle("Androidly Alert")
            setMessage("We have a message")
            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
            setNegativeButton(android.R.string.no, negativeButtonClick)
            setNeutralButton("Maybe", neutralButtonClick)
            show()    
        }
        
        
    }

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

  • Simple Alert Dialog
  • Alert Dialog With Icon and Button Customisation
  • Alert Dialog With List
  • Alert Dialog With MultiChoice List
  • Alert Dialog With Style
  • Alert Dialog With Custom Style
  • Alert Dialog With EditText

Android Studio项目结构

android basic alert dialog project structure

1. XML布局代码

下面是activity_main.xml布局的代码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnBasicAlert"
        android:layout_width="wrap_content"
        android:onClick="basicAlert"
        android:layout_height="wrap_content"
        android:text="BASIC ALERT DIALOG" />


    <Button
        android:id="@+id/btnAlertWithIconsAndCustomize"
        android:layout_width="wrap_content"
        android:onClick="withIconAndCustomise"
        android:layout_height="wrap_content"
        android:text="WITH ICON AND CUSTOMIZATION" />

    <Button
        android:id="@+id/btnAlertWithItems"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withItems"
        android:text="WITH ITEMS" />

    <Button
        android:id="@+id/btnAlertWithMultiChoiceList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withMultiChoiceList"
        android:text="WITH MULTI CHOICE LIST" />

    <Button
        android:id="@+id/btnAlertWithStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withStyle"
        android:text="WITH STYLE" />


    <Button
        android:id="@+id/btnAlertWithCustomStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withCustomStyle"
        android:text="WITH CUSTOM STYLE" />

    <Button
        android:id="@+id/btnAlertWithButtonCentered"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withButtonCentered"
        android:text="WITH BUTTON CENTERED" />

    <Button
        android:id="@+id/btnAlertWithEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withEditText"
        android:text="WITH EDIT TEXT" />


</LinearLayout>

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

2. Kotlin主活动代码
2. Kotlin主要活动代码
2. Kotlin主类代码

我们已经在上面创建了第一个提示对话框。现在让我们看看使用它的MainActivity.kt文件是什么样子的。

package net.androidly.androidlyalertdialog

import android.content.DialogInterface
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.View
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    val positiveButtonClick = { dialog: DialogInterface, which: Int ->
        Toast.makeText(applicationContext,
                android.R.string.yes, Toast.LENGTH_SHORT).show()
    }
    val negativeButtonClick = { dialog: DialogInterface, which: Int ->
        Toast.makeText(applicationContext,
                android.R.string.no, Toast.LENGTH_SHORT).show()
    }
    val neutralButtonClick = { dialog: DialogInterface, which: Int ->
        Toast.makeText(applicationContext,
                "Maybe", Toast.LENGTH_SHORT).show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    fun basicAlert(view: View){

        val builder = AlertDialog.Builder(this)

        with(builder)
        {
            setTitle("Androidly Alert")
            setMessage("We have a message")
            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
            setNegativeButton(android.R.string.no, negativeButtonClick)
            setNeutralButton("Maybe", neutralButtonClick)
            show()
        }


    }
}

3. 带有图标和自定义选项的警告对话框

val builder = AlertDialog.Builder(this)
        with(builder) {
            setTitle("Icon and Button Color")
            setMessage("We have a message")
            setPositiveButton("OK", null)
            setNegativeButton("CANCEL", null)
            setNeutralButton("NEUTRAL", null)
            setPositiveButtonIcon(resources.getDrawable(android.R.drawable.ic_menu_call, theme))
            setIcon(resources.getDrawable(android.R.drawable.ic_dialog_alert, theme))
        }
        val alertDialog = builder.create()
        alertDialog.show()

        val button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE)
        with(button) {
            setBackgroundColor(Color.BLACK)
            setPadding(0, 0, 20, 0)
            setTextColor(Color.WHITE)
        }

通过使用getButton,我们可以通过设置它们的特定常数来检索任何按钮。一旦获取到按钮,我们可以像上面那样对其进行自定义设置。

4. 带有选项的提示对话框

fun withItems(view: View) {

        val items = arrayOf("Red", "Orange", "Yellow", "Blue")
        val builder = AlertDialog.Builder(this)
        with(builder)
        {
            setTitle("List of Items")
            setItems(items) { dialog, which ->
                Toast.makeText(applicationContext, items[which] + " is clicked", Toast.LENGTH_SHORT).show()
            }

            setPositiveButton("OK", positiveButtonClick)
            show()
        }
    }

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

5. 带有多选列表的警示对话框

fun withMultiChoiceList(view: View) {

        val items = arrayOf("Microsoft", "Apple", "Amazon", "Google")
        val selectedList = ArrayList<Int>()
        val builder = AlertDialog.Builder(this)

        builder.setTitle("This is list choice dialog box")
        builder.setMultiChoiceItems(items, null
        ) { dialog, which, isChecked ->
            if (isChecked) {
                selectedList.add(which)
            } else if (selectedList.contains(which)) {
                selectedList.remove(Integer.valueOf(which))
            }
        }

        builder.setPositiveButton("DONE") { dialogInterface, i ->
            val selectedStrings = ArrayList<string>()

            for (j in selectedList.indices) {
                selectedStrings.add(items[selectedList[j]])
            }

            Toast.makeText(applicationContext, "Items selected are: " + Arrays.toString(selectedStrings.toTypedArray()), Toast.LENGTH_SHORT).show()
        }

        builder.show()

    }

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

6. 具有样式的警告对话框

fun withStyle(view: View) {

        val builder = AlertDialog.Builder(ContextThemeWrapper(this, android.R.style.Holo_SegmentedButton))

        with(builder)
        {
            setTitle("Androidly Alert")
            setMessage("We have a message")
            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
            setNegativeButton(android.R.string.no, negativeButtonClick)
            setNeutralButton("Maybe", neutralButtonClick)
            show()
        }
    }

如果您不使用ContextThemeWrapper,警报对话框会在整个屏幕上显示。

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

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

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

以下是Kotlin函数的代码:

fun withCustomStyle(view: View) {

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

        with(builder)
        {
            setTitle("Androidly Alert")
            setMessage("We have a message")
            setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
            setNegativeButton(android.R.string.no, negativeButtonClick)
            setNeutralButton("Maybe", neutralButtonClick)
            show()
        }

    }

8. 带有居中按钮的警示对话框

fun withButtonCentered(view: View) {

        val alertDialog = AlertDialog.Builder(this).create()
        alertDialog.setTitle("Title")
        alertDialog.setMessage("Message")

        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes"
        ) { dialog, which -> dialog.dismiss() }

        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No"
        ) { dialog, which -> dialog.dismiss() }
        alertDialog.show()

        val btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
        val btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE)

        val layoutParams = btnPositive.layoutParams as LinearLayout.LayoutParams
        layoutParams.weight = 10f
        btnPositive.layoutParams = layoutParams
        btnNegative.layoutParams = layoutParams
    }

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

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter the text here"/>

</LinearLayout>
fun withEditText(view: View) {
        val builder = AlertDialog.Builder(this)
        val inflater = layoutInflater
        builder.setTitle("With EditText")
        val dialogLayout = inflater.inflate(R.layout.alert_dialog_with_edittext, null)
        val editText  = dialogLayout.findViewById<EditText>(R.id.editText)
        builder.setView(dialogLayout)
        builder.setPositiveButton("OK") { dialogInterface, i -> Toast.makeText(applicationContext, "EditText is " + editText.text.toString(), Toast.LENGTH_SHORT).show() }
        builder.show()
    }
android alert dialog demo output

下载Android Studio项目:AndroidlyAlertDialog。

广告
将在 10 秒后关闭
bannerAds