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?
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()
}
}