androidkotlinandroid-dialogmotionevent

Override method for anonymous class in Kotlin for Android


My code is written in Java and I'm refactoring it to Kotlin. I have this:

Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar) {
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        dismiss();
        dialog = null;
        setLockedDialog(false);
        return false;
    }
};

I'm not able to write it using Kotlin. This is my approach:

dialog = Dialog(this, android.R.style.Theme_Translucent_NoTitleBar) {
    override fun dispatchTouchEvent(ev: MotionEvent) {
        // TODO Implement function
    }
}

My Android Studio shows me:

1- Type mismatch. Required: Boolean. Found: Int (under android.R.style.Theme_Translucent_NoTitleBar).

2- Type mismatch. Required: DialogInterface.OnCancelListener! Found: () - > Unit surrounding the overrided function.

Any suggestions?


Solution

  • Change the code to this:

    dialog = object: Dialog(this, android.R.style.Theme_Translucent_NoTitleBar) {
        override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
            // TODO Implement function
        }
    }
    

    The reason it's complaining is because 2 things. First, you need to create an object to override a function of Dialog. Second, the dispachTouchEvent wasn't returning a Boolean but unit.