kotlin XML布局來寫ALTERDailog
时间: 2023-06-23 19:09:47 浏览: 61
以下是使用 Kotlin 和 XML 布局编写 AlertDialog 的示例代码:
1. 在 res/layout/ 目录下创建一个名为 custom_dialog.xml 的布局文件,用于定义 AlertDialog 的视图:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/dialog_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dialog Title"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
android:textStyle="bold" />
<EditText
android:id="@+id/dialog_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="Enter text..." />
</LinearLayout>
```
2. 在 Kotlin 代码中创建 AlertDialog,并将上面的 custom_dialog.xml 布局文件作为其视图:
```kotlin
val builder = AlertDialog.Builder(this)
val inflater = layoutInflater
val dialogView = inflater.inflate(R.layout.custom_dialog, null)
builder.setView(dialogView)
val titleTextView = dialogView.findViewById<TextView>(R.id.dialog_title)
titleTextView.text = "Custom Dialog Title"
val inputEditText = dialogView.findViewById<EditText>(R.id.dialog_input)
inputEditText.hint = "Enter text here..."
builder.setPositiveButton("OK") { dialog, which ->
val inputText = inputEditText.text.toString()
// 执行 OK 操作
}
builder.setNegativeButton("Cancel") { dialog, which ->
dialog.dismiss()
}
val dialog = builder.create()
dialog.show()
```
在上面的代码中,我们首先使用 AlertDialog.Builder 创建一个 AlertDialog 对象。然后,我们使用 LayoutInflater 从 custom_dialog.xml 布局文件中创建一个视图,并将其设置为 AlertDialog 的视图。接下来,我们可以通过 findViewById() 方法获取布局文件中的视图,并对其进行操作。最后,我们设置 AlertDialog 的按钮操作,并显示它。
希望这可以帮助到你!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)