android.view.ContextThemeWrapper cannot be cast to android.app.Activity
This line is probably the culprit:
Activity activity = (Activity) v.getContext();
The view v
passed to the onClick()
method is the same view that you assigned the listener to, so v
is the same as holder.parentLayot
. I don't know exactly where holder.parentLayot
came from, but chances are very good that (in XML) this view (or one of its parents) has an android:theme
attribute.
When a view has the android:theme
attribute, it doesn't use its activity's context directly. Instead, the android framework will "wrap" the activity's context in a ContextThemeWrapper
in order to modify the view's theme.
To access the activity from this wrapper, you'll have to "unwrap" it. Try something like this:
private static Activity unwrap(Context context) {
while (!(context instanceof Activity) && context instanceof ContextWrapper) {
context = ((ContextWrapper) context).getBaseContext();
}
return (Activity) context;
}
Then, you can use this method in your onClick()
instead of casting the context directly:
Activity activity = unwrap(v.getContext());
Recursive solution in Kotlin:
fun Context.getActivity(): Activity? {
return when (this) {
is Activity -> this
is ContextWrapper -> this.baseContext.getActivity()
else -> null
}
}
Checked with case of using View.getContext()
.