android.view.ContextThemeWrapper cannot be cast to android.app.Activity

后端 未结 2 1480
天命终不由人
天命终不由人 2021-02-20 05:28

I\'m not a designer but when i got this project i can`t open specifically some screens, i think that they are screens and we only reuse some of the layouts have been created. An

相关标签:
2条回答
  • 2021-02-20 06:20

    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().

    0 讨论(0)
  • 2021-02-20 06:26

    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());
    
    0 讨论(0)
提交回复
热议问题