如何从视图中获取活动?

问题描述 投票:0回答:4

我有一个扩展课程。我需要活动。

public class RequestRecord extends RelativeLayout
{
    public RequestRecord(Context context)
    {
        super(context);
        ContextWrapper ctx = ((ContextWrapper) getContext());
        ScrollView sv = (ScrollView) ((Activity) 
                                   ctx).findViewById(R.id.myReqList_scroll);
   }
}

例外:java.lang.ClassCastException:android.app.ContextImpl无法强制转换为android.content.ContextWrapper

帮我?

android android-activity classcastexception
4个回答
1
投票

当我从通货膨胀获得视图而不是通过一些棘手的手动实例化时(例如,如果视图是使用应用程序上下文创建的,它将不起作用),这常常对我有用:

@NonNull
public static <T extends Activity> T findActivity(@NonNull Context context) {
    if(context == null) {
        throw new IllegalArgumentException("Context cannot be null!");
    }
    if(context instanceof Activity) {
        // noinspection unchecked
        return (T) context;
    } else {
        ContextWrapper contextWrapper = (ContextWrapper) context;
        Context baseContext = contextWrapper.getBaseContext();
        if(baseContext == null) {
            throw new IllegalStateException("Activity was not found as base context of view!");
        }
        return findActivity(baseContext);
    }
}

1
投票

getContext()返回的任何上下文对象都不会扩展ContextWrapper。此外,View可能无法访问其父Activity,也不应该知道Activity。为什么视图需要以这种方式了解另一个视图。正确的方法是,如果你想访问兄弟视图,那就是获取你的父ViewGroup并迭代它的子节点。请注意,在您进入构造函数期间,您还没有父View,因此调用getParent()将返回null。您需要在任何on *方法中执行该操作,例如:onMeasure,onLayout,onSizeChanged和onSizeChanged。


0
投票

如果ScrollView myReqList_scroll在RequestRecord中,您可以像这样调用

public class RequestRecord extends RelativeLayout
{
    public RequestRecord(Context context)
    {
        super(context);
        ScrollView sv = (ScrollView) findViewById(R.id.myReqList_scroll);
    }
}

0
投票
public static <T extends Activity> T findActivity(@NonNull Context context) {
    T activity = null;

    if (context == null) {
        return null;
    }

    if (context instanceof Activity) {
        activity = (T) context;
    } else if (context instanceof ContextWrapper) {
        ContextWrapper contextWrapper = (ContextWrapper) context;

        Context baseContext = contextWrapper.getBaseContext();

        activity = findActivity(baseContext);
    } else if (context.getClass().getName().endsWith("ContextImpl")) {
        try {
            Context baseContext = getOuterContext(context);
            activity = findActivity(baseContext);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        activity = null;
    }

    return activity;
}
© www.soinside.com 2019 - 2024. All rights reserved.