2

With Kotlin, I'm using a custom dialog class. The activity need to be closed to return the previous activity with calling finish() of the activity on the onClick() of the dialog.

The simplified custom dialog

class TestDialog (context: Context) : Dialog(context),
    View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        setContentView(R.layout.dialog_result_screen)


        var yesButton=  findViewById(R.id.buttonControl);

        yesButton.setOnClickListener(this);
    }

    override fun onClick(v: View) {
        dismiss()
        (context as AppCompatActivity).finish()
    }
}

The activity call this dialog as


 val testDialog = TestDialog(this@TheDialogDisplayerActivity)
 testDialog.show()
 //used to dislay in full size of the secreen.
 val window: Window? = testDialog.window
 window?.setLayout(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT)

The activity is extending the AppCompatActivity

When the finish() is called, the following error is occurred that I've couldn't find a solution.

java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to androidx.appcompat.app.AppCompatActivity
        at com.xyz.widget.TestResultDialog.onClick(TestResultDialog.kt:67)

I've tried casting into activity class, too. This didn't work, either.

I've looked at these Q/As 1, 2, and some other questions, too, but failed to resolve.

How can I solve this issue?

kelalaka
  • 5,064
  • 5
  • 27
  • 44

1 Answers1

2

if you look in the parent class Dialog then the context becomes : mContext = new ContextThemeWrapper(context, themeResId); - which is exactly the error it is giving you when you try and cast it back to an Activity later.

You should do :

class TestDialog (private val activity: Activity) : Dialog(activity),
    View.OnClickListener {

  ...

  override fun onClick(v: View) {
        dismiss()
        activity.finish()
    }
}
Mark
  • 9,604
  • 5
  • 36
  • 64
  • Is it recommended to explicitly call `finish()` in an Android app? Or is it better to use Intents. – IgorGanapolsky May 24 '21 at 21:10
  • @IgorGanapolsky - depends. If I want to, for example go from a splash screen onto another Activity I would use intent flags to start a new task, and not explcitly call `Activity::finish`. If I want to finish the activity I would call it - its all about usecase. However the OP's question/problem was a `ClassCastException` - anything else is out of scope of the question. – Mark May 24 '21 at 21:18