Android Kotlin中的对话框入门
Android在改善用户体验方面有突出的技术。其中之一就是使用对话。对话框是用户和应用程序之间的一个简短对话。它通常是一个在设备屏幕上弹出的小窗口。
对话框可以用来在一些事件中提示操作,或向用户传递信息。在本教程中,我们将学习如何在Android中创建和实现对话框。
前提条件
在我们继续前行之前,请确保你。
- 在你的机器上安装了[Android Studio]。
- 知道如何创建Android项目并浏览
IDE。 - 熟悉
XML和Kotlin编程语言。 - 对
Data binding有基本的了解。
开始使用
Android提供了几种类型的对话框,包括。
- 警报对话框
- 日期选择对话框
- 时间选择对话框
- 对话框片段
- 底层表格对话框
在本教程中,我们将把重点放在AlertDialog ,我们将主要包括以下概念。
-
创建警报对话框。
- 添加标题、按钮、信息和图标。
- 处理对话框事件。
-
定制警报对话框。
- 创建自定义布局资源文件。
- 使用DataBinding来访问视图。
- 创建一个圆角形的对话框。
创建一个Android项目
启动Android Studio并创建一个Empty Activity 项目,规格如下。
Name:Android中的对话框
Language:Kotlin
Min-SDK:API-21
项目设置
添加依赖性和插件
为了让我们使用DataBinding,我们必须首先启用并添加必要的插件。打开应用程序级的build.gradle 文件,在相应的范围内添加以下内容。
plugins {
id 'kotlin-kapt'
}
// inside the android block add the following
buildFeatures{
dataBinding true
}
同步并等待Gradle-build完成。一旦完成,继续设置用户界面。
设置用户界面
在我们的用户界面中,我们需要两个按钮,用来显示对话框。打开activity_main.xml 文件,粘贴下面的代码。
<Button
android:id="@+id/btnShowDefaultDialog"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="@string/show_dialog"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1" />
<Button
android:id="@+id/btnShowCustomDialog"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="@string/show_custom_dialog"
app:layout_constraintBottom_toTopOf="@id/btnShowDefaultDialog"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1" />
为了修复关于文本属性中未解决的引用的错误,在字符串资源中创建字符串,如下所示。
<resources>
<string name="show_dialog">Show dialog</string>
<string name="show_custom_dialog">Show custom dialog</string>
</resources>
按钮预览。

正如我们前面提到的,我们将使用这些按钮来显示必要的对话框。为了实现这一点,我们需要为我们布局中的每个视图提供DataBinding对象。
DataBinding的魅力在于它能自动生成这些对象。我们只需要用一个layout 标签来包围布局,如下图所示。
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--views are constrained here-->
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
编写Kotlin代码
在MainActivity.kt 文件中,我们将写出我们应用程序的逻辑。首先,创建一个类型为ActivityMainBinding 的可变变量,最初是null ,但在onCreate() 方法中被初始化。
当活动或片段被销毁时,变量或对象可能仍然持有对不存在的值的引用。这被称为内存泄漏,当然会导致我们的应用程序中出现不需要的行为。
为了避免这种情况,总是在onDestroy() 方法中取消分配给这类对象的内存。
下面的片段显示了上述讨论的概念。
class MainActivity : AppCompatActivity() {
private var activityMainBinding: ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
}
override fun onDestroy() {
activityMainBinding = null
super.onDestroy()
}
}
创建警报对话框
警报对话框是通过实例化AlertDialog 类,然后为它创建一个Builder 。在Android中,有几种类型的警报对话框。在本教程中,我们将在自己的function 中创建每个对话框,当点击按钮时,将调用相应的对话框。
A).默认警报对话框
这种类型的对话框通常是矩形的,出现在屏幕的中心。我们将在继续讨论它的功能。同时,把下面的代码粘贴到MainActivity 类里面,就在onCreate() 方法的下面。
private fun showDefaultDialog() {
val alertDialog = AlertDialog.Builder(this)
alertDialog.apply {
setTitle("Hello")
}.create().show()
}
上面的代码创建了一个标题为 "Hello "的对话框,并使用show() 方法将其显示在屏幕上。如果省略,该对话框不会弹出。你可以通过在点击按钮时调用其函数来验证这一点。添加下面的代码。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// add the following three lines
activityMainBinding?.btnShowDefaultDialog?.setOnClickListener {
showDefaultDialog()
}
}
在运行该应用程序之前,确保你的代码中没有错误。当你点击按钮时,你应该得到一个类似于下面的输出。

向对话框添加功能
现在我们已经创建了一个对话框,我们可以添加一些功能,例如。
Icon- 这是一个小尺寸的图片,出现在标题旁边。它通常使对话框的内容更丰富,更有吸引力。Message- 这是警报对话框的主要内容。它对其弹出的原因做了简短的描述,或者,提示用户在继续前进之前做一个决定。Buttons- 它们出现在对话框的底部部分。有三种类型的按钮,即: 、 和 按钮。顾名思义,它们一旦被点击就会执行相应的操作。默认情况下,一旦点击任何一个按钮,对话框就会关闭。PositiveNegativeNeutralView- 这是一个用于定制对话框的布局。我们稍后会了解到这一点。
同时,让我们创建一个实现上述功能的对话框。创建一个名为ic_hello 的矢量可画(图标)。
更新showDefaultDialog() ,使其看起来像下面的函数。
private fun showDefaultDialog() {
val alertDialog = AlertDialog.Builder(this)
alertDialog.apply {
setIcon(R.drawable.ic_hello)
setTitle("Hello")
setMessage("I just wanted to greet you. I hope you are doing great!")
setPositiveButton("Positive") { _, _ ->
toast("clicked positive button")
}
setNegativeButton("Negative") { _, _ ->
toast("clicked negative button")
}
setNeutralButton("Neutral") { _, _ ->
toast("clicked neutral button")
}
}.create().show()
}
现在,复制并粘贴下面的代码,就在showDefaultDialog() 函数的上方或下方。
private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
解释
创建按钮的语法要求我们在lambda函数中传入一个类型为DialogInterface.OnClickListener 的监听器。DialogInterface 定义了一个对话框类型的类,它可以被显示、取消(或驳回),并且可以有可以被点击的按钮。Kotlin ,通过允许我们在lambda函数中传入underscores ,来简化这个过程,以获得未使用的参数。
该函数toast() ,用于在点击按钮时显示一个简短的Toast ,其文本作为参数传入。
运行该应用程序,你应该看到一个与下面类似的对话框。

请注意,当你在对话框外点击时,它就会解散。你可以通过在构建器中添加setCancelable(false) 来避免这种效果。
B).自定义警报对话框
自定义是使某些东西的出现或行为与默认的方式不同的行为。警报对话框为我们提供了一个重要的方法,setView() ,它允许我们使用一个Layout 作为对话框的View 。这样的对话框被称为自定义对话框。
接着,创建一个名为lay_custom_dialog 的XML布局资源文件。我们将使用这个布局来达到上面提到的目的。
打开新创建的文件,粘贴以下代码
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View
android:id="@+id/view"
android:layout_width="0dp"
android:layout_height="40dp"
android:background="#FF0057"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/greetings_sent_successfully"
android:textColor="@color/white"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="@id/view"
app:layout_constraintEnd_toEndOf="@id/view"
app:layout_constraintStart_toStartOf="@id/view"
app:layout_constraintTop_toTopOf="@id/view" />
<ImageView
android:layout_width="0dp"
android:layout_height="150dp"
android:layout_margin="10dp"
android:src="@drawable/ic_hello"
app:layout_constraintBottom_toTopOf="@+id/btnOk"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/view" />
<com.google.android.material.button.MaterialButton
android:id="@+id/btnOk"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:backgroundTint="#FF0057"
android:text="@string/ok"
android:textStyle="bold"
app:cornerRadius="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
为了修复关于 "text "属性中未解决的引用的错误,复制并粘贴下面各自的字符串资源。
<resources>
<string name="app_name">Dialogs in Android</string>
<string name="show_dialog">Show dialog</string>
<string name="show_custom_dialog">Show custom dialog</string>
<string name="ok">OK</string>
<string name="greetings_sent_successfully">Greetings sent successfully</string>
</resources>
在MainActivity.kt 文件中,粘贴以下代码,就在showDefaultDialog() 函数下面。
private fun showCustomDialog() {
val dialogBinding: LayCustomDialogBinding? =
DataBindingUtil.inflate(
LayoutInflater.from(this),
R.layout.lay_custom_dialog,
null,
false
)
val customDialog = AlertDialog.Builder(this, 0).create()
customDialog.apply {
setView(dialogBinding?.root)
setCancelable(false)
}.show()
dialogBinding?.btnOk?.setOnClickListener {
customDialog.dismiss()
}
}
在这里,我们已经链接了布局并创建了一个不可取消的对话框,只能通过点击Ok 按钮来取消。
在onCreate() 方法中,添加以下代码。
activityMainBinding?.btnShowCustomDialog?.setOnClickListener {
showCustomDialog()
}
我们可以通过创建圆角来进一步定制它。为了实现这一点,我们将创建一个具有圆形的可画资源文件,然后将其设置为我们布局的背景。创建一个名为round_corners 的可画资源文件,并在其中粘贴以下代码。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/white">
<corners android:radius="20dp" />
</shape>
记住要把它设置为根ViewGroup 的背景,如下图所示。
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/round_corners"
>
在运行该应用程序之前,我们需要做以下工作。
- 创建一个名为
curved_view的顶部弯曲形状的可画资源,并将其设置为视图的背景 - 将对话窗口的颜色设置为透明。这将使圆角可见,因为窗口的背景将不可见。
将下面的代码分别粘贴在curved_view.xml 文件和showCustomDialog() 函数中。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FF0057"/>
<corners android:topLeftRadius="20dp" android:topRightRadius="20dp"/>
</shape>
customDialog.apply {
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setView(dialogBinding?.root)
setCancelable(false)
}.show()
该函数的其余部分保持不变。
现在我们完成了。运行该应用程序,你应该看到一个与此类似的对话框

总结
在本教程中,我们已经学会了如何在Android中创建、定制和使用警报对话框。正如你所看到的,对话框的实现非常简单。