Hi I am trying to convert this code to Kotlin. but unable to
Ide could not automatically convert it
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
// Prevent dialog close on back press button
return keyCode == KeyEvent.KEYCODE_BACK;
}
});
Interface
interface OnKeyListener {
/**
* Called when a key is dispatched to a dialog. This allows listeners to
* get a chance to respond before the dialog.
*
* @param dialog the dialog the key has been dispatched to
* @param keyCode the code for the physical key that was pressed
* @param event the KeyEvent object containing full information about
* the event
* @return {@code true} if the listener has consumed the event,
* {@code false} otherwise
*/
boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event);
}
What I tried
dialog.setOnKeyListener(
DialogInterface.OnKeyListener { dialog, keyCode, event ->
}
)
Create a dialog:
val alertDialog: AlertDialog? = activity?.let {
val builder = AlertDialog.Builder(it)
builder.apply {
setPositiveButton(R.string.ok,
DialogInterface.OnClickListener { dialog, id ->
// User clicked OK button
})
setNegativeButton(R.string.cancel,
DialogInterface.OnClickListener { dialog, id ->
// User cancelled the dialog
})
}
// Set other dialog properties
...
// Create the AlertDialog
builder.create()
}
Set keyListener:
//this way
alertDialog?.setOnKeyListener(object : DialogInterface.OnKeyListener {
override fun onKey(dialog: DialogInterface?, keyCode: Int, event: KeyEvent?): Boolean {
TODO("Not yet implemented")
}
})
//or this way
alertDialog?.setOnKeyListener { dialog, keyCode, event -> TODO("Not yet implemented") }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.