如果我直接在
oCreate()
中添加showPopupWindow();
,会出现以下错误:如下所示:android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
showPopupWindow();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPopupWindow();
}
});
}
private void showPopupWindow() {
TextView textView = new TextView(this);
textView.setText("This is a Text");
textView.setTextSize(20);
textView.setTextColor(Color.parseColor("#33000000"));
//悬浮窗体
popupWindow = new PopupWindow(textView,-2,-2);
//设置View
popupWindow.setContentView(textView);
//设置宽高
//必须设置背景
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
//父窗体,Gravity,位置(x距离左边的距离,y距离上边的距离)
popupWindow.showAtLocation(findViewById(R.id.rl_main), Gravity.LEFT + Gravity.TOP, 60, 60);
}
但如果我把它添加到 onClick
中,就可以正常工作,像下面这样:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showPopupWindow();
}
});
}
private void showPopupWindow() {
TextView textView = new TextView(this);
textView.setText("This is a Text");
textView.setTextSize(20);
textView.setTextColor(Color.parseColor("#33000000"));
//悬浮窗体
popupWindow = new PopupWindow(textView,-2,-2);
//设置View
popupWindow.setContentView(textView);
//设置宽高
//必须设置背景
popupWindow.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
//父窗体,Gravity,位置(x距离左边的距离,y距离上边的距离)
popupWindow.showAtLocation(findViewById(R.id.rl_main), Gravity.LEFT + Gravity.TOP, 60, 60);
}
请帮助我理解这个。