AlertDialog 本身并不能用作一个 png 格式的按钮,因为它是一个弹出式对话框,而不是一个按钮。 不过,您可以使用自定义的布局将 AlertDialog 显示为一个按钮,具体方法如下:
首先,创建一个 xml 文件,并在其中定义您想要的图像按钮。例如,您可以使用 ImageView、Button 或 ImageButton。
在您的代码中,创建一个 AlertDialog 对象,然后使用 setView() 方法将其设置为您刚刚创建的布局文件。 此外,您还可以通过 setCancelable() 方法将 AlertDialog 设置为非取消属性。
最后,使用 show() 方法将 AlertDialog 显示为一个按钮。
以下是一个具有如上要求的 Kotlin 代码示例:
val builder = AlertDialog.Builder(this)
val inflater = this.layoutInflater
val customLayout = inflater.inflate(R.layout.custom_layout,null)
builder.setView(customLayout)
builder.setCancelable(false)
val alertDialog = builder.create()
alertDialog.show()
val customButton = customLayout.findViewById(R.id.custom_button)
customButton.setOnClickListener {
// your button logic here
alertDialog.dismiss()
}
custom_layout.xml 文件的代码示例如下:
上一篇:AlertDialog简化