KOTLIN 繼承DAILOG接口寫一個自定的DAILOG,配合XML
时间: 2023-06-24 20:08:00 浏览: 35
好的,首先我们需要创建一个继承自Dialog类的自定义Dialog类。示例代码如下:
```kotlin
class MyDialog(context: Context) : Dialog(context), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.dialog_my)
// 设置对话框的宽度和高度
window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)
// 设置对话框的点击事件
findViewById<Button>(R.id.btn_confirm).setOnClickListener(this)
findViewById<Button>(R.id.btn_cancel).setOnClickListener(this)
}
override fun onClick(view: View?) {
when (view?.id) {
R.id.btn_confirm -> {
// 点击确认按钮时执行的操作
dismiss()
}
R.id.btn_cancel -> {
// 点击取消按钮时执行的操作
cancel()
}
}
}
}
```
在上面的代码中,我们首先创建了一个名为MyDialog的自定义Dialog类,并实现了Dialog和View.OnClickListener接口。在onCreate()方法中,我们设置了对话框的布局文件和点击事件。在onClick()方法中,我们根据点击的按钮执行不同的操作,如果点击的是确认按钮,则关闭对话框;如果点击的是取消按钮,则取消对话框。
接下来,我们需要在res目录下创建一个XML布局文件,该文件用于定义对话框的界面。示例代码如下:
```xml
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定义对话框"
android:textSize="18sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/colorDivider" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这是一个自定义对话框的示例,你可以在这里添加你自己的布局和逻辑。" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/colorDivider" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:orientation="horizontal">
<Button
android:id="@+id/btn_cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="取消" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@color/colorDivider" />
<Button
android:id="@+id/btn_confirm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="确认" />
</LinearLayout>
</LinearLayout>
```
在上面的代码中,我们创建了一个名为dialog_my.xml的布局文件,该文件包含一个标题栏、一个消息内容区和两个按钮。我们可以根据自己的需要修改布局文件的内容和样式。
最后,我们可以在Activity中调用MyDialog类来显示自定义对话框。示例代码如下:
```kotlin
val dialog = MyDialog(this)
dialog.show()
```
在上面的代码中,我们首先创建了一个MyDialog对象,然后调用show()方法显示对话框。这样就完成了自定义对话框的创建和使用。