gpt4 book ai didi

android - 在 Android Activity 中创建弹出窗口的问题

转载 作者:IT王子 更新时间:2023-10-28 23:41:41 25 4
gpt4 key购买 nike

我正在尝试创建一个仅在应用程序第一次启动时出现的弹出窗口。我希望它显示一些文本并有一个按钮来关闭弹出窗口。但是,我无法让 PopupWindow 正常工作。我尝试了两种不同的方法:

首先,我有一个 XML 文件,它声明了名为 popup.xml 的弹出窗口的布局(一个线性布局内的 TextView ),我已将其添加到我的主 Activity 的 OnCreate() 中:

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

第二次我对这段代码做了同样的事情:

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 并显示“无法添加窗口 -- token null 无效”

我到底做错了什么?我非常新手,请多多包涵。

最佳答案

为避免 BadTokenException,您需要推迟显示弹出窗口,直到调用所有生命周期方法(-> 显示 Activity 窗口):

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

关于android - 在 Android Activity 中创建弹出窗口的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4187673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com