Reputation: 268
I have been facing some issues while converting my android JAVA code into KOTLIN. I want to show a Material Dialog on some condition and want control back to activity as soon as the user clicks on dialog's button.
My java code:
public static void showAlertPopup(Context context, String title, String message) {
try {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(context);
builder.setTitle(title != null ? title : context.getString(R.string.alertTitle));
builder.setMessage(message);
builder.setCancelable(false);
builder.setIcon(ContextCompat.getDrawable(context, R.drawable.ic_alert));
builder.setPositiveButton(context.getString(R.string.txtNeutralBtn),
(dialogInterface, i) -> dialogInterface.dismiss());
builder.setBackground(ContextCompat.getDrawable(context, R.drawable.dialog_background));
builder.show();
} catch (Exception e) {
DLiteLogger.WriteLog(MaterialDialogUtility.class, AppSettings.LogLevel.Error, e.getMessage());
}
}
My conversion to Kotlin:
fun showErrorPopup(
context: Context,
message: String?,
callback: OnPositiveButtonClickListener?
) {
MaterialAlertDialogBuilder(context).also {
it.setTitle(context.getString(R.string.errorTitle))
it.setMessage(message)
it.setCancelable(false)
it.setIcon(ContextCompat.getDrawable(context, R.drawable.ic_error))
it.setPositiveButton(context.getString(R.string.txtNeutralBtn))
{ dialogInterface: DialogInterface, _: Int ->
if (callback != null) {
dialogInterface.dismiss()
callback.onPositiveBtnClick(dialogInterface)
} else dialogInterface.dismiss()
}
it.background = ContextCompat.getDrawable(context, R.drawable.dialog_background)
it.show()
}
}
This is the interface I have created in same class:
interface OnPositiveButtonClickListener {
fun onPositiveBtnClick(dialog: DialogInterface?)
}
The issue I am facing currently for below code:
MaterialDialogUtility.showErrorPopup(this@LoginActivity,
getString(R.string.alertIncorrectPassword),
{ dialog ->
Objects.requireNonNull(binding.passwordEt.getText()).clear()
})
is
Type mismatch: inferred type is ([ERROR : ]) -> [ERROR : Cannot infer type variable TypeVariable(_L)] but MaterialDialogUtility.OnPositiveButtonClickListener? was expected
Upvotes: 0
Views: 1885
Reputation: 1258
In order to use your interface as a lambda you'll have to convert it to a SAM interface a.k.a functional interface. So something like this:
fun interface OnPositiveButtonClickListener {
fun onPositiveBtnClick(dialog: DialogInterface?)
}
More description about functional interfaces here.
If you don't want to use SAM you can still use your current interface like this:
showErrorPopup(
this,
"Some String",
callback = object: OnPositiveButtonClickListener{
override fun onPositiveBtnClick(dialog: DialogInterface?) {
TODO("Not yet implemented")
}
}
)
Upvotes: 1