0
public AsyncSyncWithCloud(HistoryFragmentActivity historyFragmentActivity) {
    this.historyFragmentActivity = historyFragmentActivity;
    progressDialog = new ProgressDialog(historyFragmentActivity);

    // ???
    // java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to xxx.charting.HistoryFragmentActivity
    HistoryFragmentActivity test = ((HistoryFragmentActivity)progressDialog.getContext());
}

我想知道,为什么我将自己Activity的上下文作为上下文传递给ProgressDialog. 当我getContext从 progressDialog 执行时,我没有得到我之前传入的内容?

4

2 回答 2

0

不确定这是一个好的解决方案

    private HistoryFragmentActivity getHistoryFragmentActivity(ProgressDialog progressDialog) {
        return (HistoryFragmentActivity)(((android.content.ContextWrapper)progressDialog.getContext()).getBaseContext());
    }
于 2012-07-11T09:06:07.360 回答
0

如您所见,上下文已被包装。

如果您向下钻取,您将在构造函数中找到:-

    Dialog(Context context, int theme, boolean createContextThemeWrapper) {
    if (createContextThemeWrapper) {
        if (theme == 0) {
            TypedValue outValue = new TypedValue();
            context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,
                    outValue, true);
            theme = outValue.resourceId;
        }
        mContext = new ContextThemeWrapper(context, theme);
    } else {
        mContext = context;
    }

    mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
    Window w = PolicyManager.makeNewWindow(mContext);
    mWindow = w;
    w.setCallback(this);
    w.setOnWindowDismissedCallback(this);
    w.setWindowManager(mWindowManager, null, null);
    w.setGravity(Gravity.CENTER);
    mListenersHandler = new ListenersHandler(this);
}

当当前没有设置主题时,它会包装上下文。

虽然您可以按照自己的方式进行投射,但我不确定它的可靠性如何——您可以对其进行 instanceof 检查,但可能需要从一个全新的角度看待整个事情。

通常,从片段中获取活动的最佳方法是使用 getActivity() 并改为强制转换。更好的是附加一个监听器 onAttach() 方法:

Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        listener = (Listener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(TAG
                + " must implement Listener");
    }
}

@Override
public void onDetach() {
    listener = null;
    super.onDetach();
}
于 2014-12-24T00:40:16.300 回答