kotlin 对话框
In this tutorial, we’ll be discussing Alert Dialogs and implement them in our Android Application using Kotlin.
在本教程中,我们将讨论警报对话框,并使用Kotlin在我们的Android应用程序中实现它们。
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.
有三个构建警报对话框的核心组件。
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.
我们在构造函数内部传递上下文。 (可选)我们可以传递另一个参数,即警告对话框样式。
Some of the methods that can be used on an AlertDialog.
可以在AlertDialog上使用的一些方法。
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函数 。 在dialog
和which
代表了两个参数。
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。
Kotlin has still more power to improve the readability of the above code.
Kotlin仍然具有提高上述代码的可读性的能力。
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中实现以下功能。
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类中触发。 我们将一次讨论每个。
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()
}
}
}
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。
检索到按钮后,我们可以像上面一样自定义按钮。
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
参数表示在列表中单击的元素的索引。
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消息中显示它们。
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,则“警报”对话框将显示在全屏上。
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()
}
}
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
}
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:
以上应用程序的输出如下:
翻译自: https://www.journaldev.com/309/android-alert-dialog-using-kotlin
kotlin 对话框