如果我直接将showPopupWindow();添加到oCreate()中,它将产生一个错误:
android.view.WindowManager$BadTokenException:无法添加窗口-令牌null无效;您的活动正在运行吗?
如下所示:
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);
}请帮助我理解它。
发布于 2015-08-14 05:16:02
我想说,在onCreate()方法中显示弹出窗口还为时过早,因为在此之前,活动可能还没有完成所需的生命周期。您需要通过实现秒级的延迟来区别您的解决方案。
发布于 2015-08-14 06:04:17
使用Handler而不是Thread.sleep()
Handler handler = new Handler();然后在setContentView()之后;
handler.postDelayed(new Runnable()
{
@Override
public void run()
{
showPopupWindow();
}
}, 2000);https://stackoverflow.com/questions/32002654
复制相似问题