kotlin 对话框_使用Kotlin的Android警报对话框

kotlin 对话框

In this tutorial, we’ll be discussing Alert Dialogs and implement them in our Android Application using Kotlin.

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

警报对话框 (Alert Dialogs)

Alert Dialog is a window that pops up on the screen. They generally show some information and ask for a user action.

“警报对话框”是一个在屏幕上弹出的窗口。 它们通常会显示一些信息并要求用户采取措施。

There are three core components that build an Alert Dialog.

有三个构建警报对话框的核心组件。

  • Title Text

    标题文字
  • Message Text

    讯息文字
  • Buttons – There are three types of buttons: Positive, Negative, and Neutral

    按钮–共有三种类型的按钮:正,负和中性

To create an AlertDialog we use the AlertDialog.Builder inner class.

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

val alertDialogBuilder = AlertDialog.Builder(this)

We pass the context inside the constructor. Optionally, we can pass another parameter, the alert dialog style.

我们在构造函数内部传递上下文。 (可选)我们可以传递另一个参数,即警告对话框样式。

警报对话框方法 (Alert Dialog Methods)

Some of the methods that can be used on an AlertDialog.

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

  • setTitle

    setTitle
  • setMessage

    setMessage
  • setIcon

    setIcon
  • setCustomTitle – Here you can pass a custom view that’ll be put in place of the title part in the alert dialog.

    setCustomTitle –在这里您可以传递自定义视图,该视图将代替警报对话框中的标题部分。
  • setPositiveButton – We pass the string name, as well as Button, clicked callback method here.

    setPositiveButton –我们在此处传递字符串名称以及Button单击的回调方法。
  • setView – used to add a custom view inside the alert dialog.

    setView –用于在警报对话框中添加自定义视图。
  • setList – used to set an array of strings which would be displayed in the form of a List.

    setList –用于设置将以列表形式显示的字符串数组。
  • setMultiChoiceList – again we can set an array but this time we can select multiple items from the List thanks to CheckBox.

    setMultiChoiceList –同样,我们可以设置一个数组,但是这次我们可以通过CheckBox从列表中选择多个项目。
  • setPositiveButtonIcon – set an icon alongside the Button

    setPositiveButtonIcon –在按钮旁边设置图标
  • show() – used to display the AlertDialog

    show()–用于显示AlertDialog
  • setDismissListener – Inside this, you can set the logic to be triggered when the alert dialog is dismissed.

    setDismissListener –在其中,您可以设置关闭警报对话框时要触发的逻辑。
  • setShowListener – set the logic to be triggered when the alert dialog is dismissed.

    setShowListener –设置关闭警报对话框时要触发的逻辑。
  • 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.

    setCancelable –需要一个布尔值。 默认情况下,单击按钮或触摸外部时,所有警报对话框都是可取消的。 如果此方法设置为false,则需要使用dialog.cancel()方法显式取消对话框。

警报对话框Kotlin代码 (Alert Dialog Kotlin Code)

To use AlertDialog in your Android Studio project, import the following class.

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

import android.support.v7.app.AlertDialog;

Following Kotlin code is used to create a simple alert dialog.

以下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()

The builder.show() displays the Alert Dialog on the screen.

builder.show()在屏幕上显示警报对话框。

Inside the setPositiveButton function, we pass the Button text along with a Kotlin function that’s triggered when that button is clicked. The function is a part of the DialogInterface.OnClickListener() interface.

setPositiveButton函数内部,我们传递Button文本以及单击该按钮时触发的Kotlin函数。 该函数是DialogInterface.OnClickListener()接口的一部分。

The function type is (DialogInterface, Int) -> Unit. DialogInterface is an instance of the Dialog and Int is the id of the button that is clicked.

函数类型为(DialogInterface, Int) -> Unit 。 DialogInterface是Dialog的一个实例,而Int是单击的按钮的ID。

In the above code, we’ve represented this function as a Higher Order Kotlin function. The dialog and which represents the two arguments.

在上面的代码中,我们已将此函数表示为高阶Kotlin函数 。 在dialogwhich代表了两个参数。

We can improve the function by passing _ if the arguments aren’t used.

如果不使用参数,我们可以通过传递_来改进功能。

The functions would look like these:

函数如下所示:

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

Alternatively, we can also display the Dialog through the AlertDialog class instance.

或者,我们也可以通过AlertDialog类实例显示Dialog。

Replace builder.show() with:

builder.show()替换为:

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

Instead of defining the button click listener functions for each of the buttons, we can define the higher-order functions separately as well.

除了可以为每个按钮定义按钮单击侦听器功能之外,我们还可以分别定义高阶功能。

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

Now set this val property inside the setPositiveButton Kotlin function as:

现在在setPositiveButton Kotlin函数中将此val属性设置为:

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

The latter makes the code look much concise.

后者使代码看起来更加简洁。

Following is a screenshot from our Activity class with the above function applied for each of the Buttons.

以下是我们的Activity类的屏幕截图,其中上述功能适用于每个Button。

You can pass a null instead of the function if you don’t intend to keep any action on the button click.
如果您不想在单击按钮时保持任何操作,则可以传递null而不是函数。

Kotlin has still more power to improve the readability of the above code.

Kotlin仍然具有提高上述代码的可读性的能力。

简单警报对话框Kotlin代码 (Simple Alert Dialog Kotlin code)

Using the with function, we can enhance the readability of the Kotlin code to create an Alert Dialog.

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

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()    
        }
        
        
    }

In the next section we’ll be creating our Android Application where we will implement the following features in our AlertDialog.

在下一节中,我们将创建我们的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

    带EditText的警报对话框

Android Studio项目结构 (Android Studio Project Structure)

1. XML布局代码 (1. XML Layout Code)

The code for the activity_main.xml layout is given below.

下面给出了activity_main.xml布局的代码。




    

For each of the buttons we’ve set an android:onClick attribute with the function name. These Kotlin functions would be triggered in the MainActivity.kt class. We’ll discuss each of them one at a time.

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

2. Kotlin主要活动代码 (2. Kotlin Main Activity Code)

We’ve already created the first Alert Dialog above. Let’s see how the MainActivity.kt looks with it.

我们已经在上面创建了第一个警报对话框。 让我们看一下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.带有图标和自定义的警报对话框 (3. Alert Dialog With Icons and Customisation)

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

Using the getButton, we can retrieve any of the Buttons by setting their respective constant.
Once the Button is retrieved, we can customise it as done above.

使用getButton ,我们可以通过设置它们各自的常量来检索任何Button。
检索到按钮后,我们可以像上面一样自定义按钮。

4.带有项目的警报对话框 (4. Alert Dialog With Items)

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()
        }
    }

Inside the setItems we pass the Kotlin Array.
The which argument represents the index of the element clicked in the List.

在setItems内部,我们传递了Kotlin Array。
which参数表示在列表中单击的元素的索引。

5.带有多重选择列表的警报对话框 (5. Alert Dialog With MultiChoice List)

fun withMultiChoiceList(view: View) {

        val items = arrayOf("Microsoft", "Apple", "Amazon", "Google")
        val selectedList = ArrayList()
        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()

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

    }

In the above code, we save the choices in an array list of integers and retrieve them again to show them in the Toast message.

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

6.带有样式的警报对话框 (6. Alert Dialog With Style)

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()
        }
    }

If you don’t use ContextThemeWrapper, the Alert Dialog would be displayed on the full screen.

如果您不使用ContextThemeWrapper,则“警报”对话框将显示在全屏上。

7.具有自定义样式的警报对话框 (7. Alert Dialog With Custom Style)

Add the following code in the styles.xml file:

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

Following is the Kotlin function:

以下是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.带有按钮居中的警报对话框 (8. Alert Dialog With Button Centered)

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.带有编辑文本的警报对话框 (9. Alert Dialog With Edit Text)

The code for the custom layout alert_dialog_with_edittext.xml is given below:

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




    

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(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()
    }

The output of the above application is given below:

以上应用程序的输出如下:

AndroidlyAlertDialog AndroidlyAlertDialog

翻译自: https://www.journaldev.com/309/android-alert-dialog-using-kotlin

kotlin 对话框

你可能感兴趣的:(kotlin 对话框_使用Kotlin的Android警报对话框)