以下是Kotlin中创建一个AlertDialog的示例代码,其中包括三个按钮,XML不寫按鍵,在代碼裡稍微向移動5dp
时间: 2023-06-25 22:04:29 浏览: 83
android AlertDialog的简单使用实例
```kotlin
val builder = AlertDialog.Builder(this)
builder.setTitle("Title")
builder.setMessage("Message")
// Positive Button
builder.setPositiveButton("Yes") { dialog, which ->
// Do something when positive button is clicked
}
// Negative Button
builder.setNegativeButton("No") { dialog, which ->
// Do something when negative button is clicked
}
// Neutral Button
builder.setNeutralButton("Cancel") { dialog, which ->
// Do something when neutral button is clicked
}
val dialog = builder.create()
dialog.show()
// Move the buttons down by 5dp
val positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
val negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
val neutralButton = dialog.getButton(AlertDialog.BUTTON_NEUTRAL)
val layoutParams = positiveButton.layoutParams as LinearLayout.LayoutParams
layoutParams.setMargins(0, 0, 0, 5.dpToPx())
positiveButton.layoutParams = layoutParams
val layoutParams2 = negativeButton.layoutParams as LinearLayout.LayoutParams
layoutParams2.setMargins(0, 0, 0, 5.dpToPx())
negativeButton.layoutParams = layoutParams2
val layoutParams3 = neutralButton.layoutParams as LinearLayout.LayoutParams
layoutParams3.setMargins(0, 0, 0, 5.dpToPx())
neutralButton.layoutParams = layoutParams3
fun Int.dpToPx(): Int {
val scale = resources.displayMetrics.density
return (this * scale + 0.5f).toInt()
}
```
阅读全文