异常类型为:android.view.WindowManager$BadTokenException: Unable to add window
我在fragment中public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {中试图调用对话框静态工具类时出现该异常:当时上下文环境使用
context = getActivity().getApplicationContext();
调用方法为:
mp = new MyProgress(context);
mp.start();
静态工具类为:
package com.srit.zcxc.myview;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MyProgress extends View {
private AlertDialog.Builder builder = null;
private AlertDialog dialog = null;
private LinearLayout linear = null;
public MyProgress(Context context) {
super(context);
builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
linear = new LinearLayout(context);
linear.setOrientation(LinearLayout.VERTICAL);
linear.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
linear.setBackgroundColor(Color.BLACK);
linear.setGravity(Gravity.CENTER);
linear.setPadding(5, 5, 5, 5);
ProgressBar pb = new ProgressBar(context);
linear.addView(pb);
TextView tv = new TextView(context);
tv.setGravity(Gravity.CENTER);
tv.setText("取消登录");
tv.setTextColor(Color.WHITE);
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
stop();
}
});
linear.addView(tv);
builder.setView(linear);
}
public void setBackgroundDrawableByresourceId(int resourceId) {
linear.setBackgroundResource(resourceId);
}
public void start() {
dialog = builder.show();
}
public void stop() {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
public boolean isShowing() {
return dialog.isShowing();
}
}
解决方法为:
mp = new MyProgress(this.getActivity());
mp.start();
产生异常的原因:
获取上下文this.getApplicationContext())和 this的区别:
这里的this指的当然就是Acitivity.this , 指的是这个Acitivity的上下文,而this.getApplicationContext()指的则是整个应用
的上下文。
对于AlertDialog来说,是需要依赖一个View,而View是对应于Activity的。
那么为什么会报错呢,这里涉及到一个生命周期的问题了。
对于一个应用Context来说,它的生命周期是整个应用程序的生命周期,而对于Activity来说,当它销毁之后它的生命
周期就结束了。
AlertDialog是属于Acitivity的,当Activity销毁的时候它也必须销毁,所以这里我们指定是Activity的Context。