问题创造了Android的活动一个弹出窗口弹出窗口、创造了、问题、Android

2023-09-12 10:55:26 作者:十年过客

我想创建一个只出现在第一时间应用程序启动时弹出一个窗口。我希望它显示一些文本,并有一个按钮来关闭弹出。不过,我有麻烦得到PopupWindow甚至工作。我试着做这件事的两种不同的方式:

I'm trying to create a popup window that only appears the first time the application starts. I want it to display some text and have a button to close the popup. However, I'm having troubles getting the PopupWindow to even work. I've tried two different ways of doing it:

首先我有一个声明弹出称为popup.xml(一的LinearLayout内一个TextView)的布局的XML文件,(我的主要活动中,我添加了这个在OnCreate):

First I have an XML file which declares the layout of the popup called popup.xml (a textview inside a linearlayout) and I've added this in the OnCreate() of my main Activity:

PopupWindow pw = new PopupWindow(findViewById(R.id.popup), 100, 100, true);
    pw.showAtLocation(findViewById(R.id.main), Gravity.CENTER, 0, 0);

其次,我做了完全一样的这个code:

Second I did the exact same with this code:

final LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    PopupWindow pw = new PopupWindow(inflater.inflate(R.layout.popup, (ViewGroup) findViewById(R.layout.main) ), 100, 100, true);
    pw.showAtLocation(findViewById(R.id.main_page_layout), Gravity.CENTER, 0, 0);

首先抛出一个NullPointerException异常,第二抛出BadTokenException并说无法添加窗口 - 标记空是无效的

The first throws a NullPointerException and the second throws a BadTokenException and says "Unable to add window -- token null is not valid"

在世界上什么我做错了什么?我非常新手,请多多包涵。

What in the world am I doing wrong? I'm extremely novice so please bear with me.

推荐答案

要避免BadTokenException,你需要推迟显示弹出,直到所有的生命周期方法被调用后( - 显示>活动窗口):

To avoid BadTokenException, you need to defer showing the popup until after all the lifecycle methods are called (-> activity window is displayed):

 findViewById(R.id.main_page_layout).post(new Runnable() {
   public void run() {
     pw.showAtLocation(findViewById(R.id.main_page_layout), Gravity.CENTER, 0, 0);
   }
});