kotlin 在fragment中写Dialog
时间: 2023-10-11 16:15:15 浏览: 47
要在 Kotlin 的 Fragment 中编写对话框,可以使用 Android 的内置 `AlertDialog` 类。以下是一个示例代码:
```kotlin
class MyFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
showDialog()
}
private fun showDialog() {
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Dialog Title")
.setMessage("Dialog Message")
.setPositiveButton("OK") { dialog, which ->
// Do something when the user clicks the OK button
}
.setNegativeButton("Cancel") { dialog, which ->
// Do something when the user clicks the Cancel button
}
val dialog = builder.create()
dialog.show()
}
}
```
在 `showDialog()` 方法中,我们首先创建了一个 `AlertDialog.Builder` 对象,然后设置对话框的标题和消息。接下来,我们为“OK”和“Cancel”按钮设置回调函数,并将这些按钮添加到对话框中。最后,我们创建对话框并显示它。