KOTLIN 繼承DAILOG接口寫一個自定的DAILOG,配合XML
时间: 2023-06-24 07:08:14 浏览: 41
好的,下面是一个示例代码,演示如何使用 Kotlin 编写一个自定义的 Dialog,并与 XML 文件配合使用。
首先,我们需要创建一个类,实现 Android 系统自带的 Dialog 接口,例如:
```kotlin
class MyDialog(context: Context, private val message: String) : Dialog(context) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dialog_my)
// 设置对话框文本
findViewById<TextView>(R.id.tv_message).text = message
// 设置对话框按钮点击事件
findViewById<Button>(R.id.btn_ok).setOnClickListener {
dismiss() // 关闭对话框
}
}
}
```
在上面的代码中,我们创建了一个名为 MyDialog 的类,并在构造函数中传入了一个 Context 对象和一个消息文本。在 onCreate 方法中,我们首先调用父类的 onCreate 方法,然后使用 setContentView 方法将对话框的布局文件 dialog_my.xml 加载到对话框中。接着,我们使用 findViewById 方法获取布局文件中的 TextView 和 Button 控件,并设置对应的文本和点击事件。最后,我们在按钮点击事件中调用 dismiss 方法关闭对话框。
接下来,我们需要创建一个 XML 布局文件 dialog_my.xml,例如:
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/tv_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="@android:color/black"
android:text="Hello, World!" />
<Button
android:id="@+id/btn_ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="OK" />
</LinearLayout>
```
在上面的代码中,我们使用 LinearLayout 控件作为根布局,内部包含一个 TextView 和一个 Button 控件。TextView 显示对话框的消息文本,Button 用于关闭对话框。
最后,我们可以在 Activity 中使用 MyDialog 类来显示自定义的对话框,例如:
```kotlin
val dialog = MyDialog(this, "Welcome to Kotlin!")
dialog.show()
```
在上面的代码中,我们首先创建了一个 MyDialog 对象,并传入了一个消息文本。然后调用 show 方法显示对话框。
以上就是一个使用 Kotlin 编写自定义 Dialog 并与 XML 文件配合使用的示例。