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
。当我从progressDialog执行getContext
时,我没有得到我之前传递的内容?
答案 0 :(得分:0)
不确定这是不错的解决方案
private HistoryFragmentActivity getHistoryFragmentActivity(ProgressDialog progressDialog) {
return (HistoryFragmentActivity)(((android.content.ContextWrapper)progressDialog.getContext()).getBaseContext());
}
答案 1 :(得分: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();
}