gpt4 book ai didi

java - Android自定义对话框报错

转载 作者:行者123 更新时间:2023-12-01 08:07:01 25 4
gpt4 key购买 nike

在我的android应用程序中,我必须在按钮点击事件上弹出一个对话框。但是,当我单击按钮时,应用程序停止工作。我将预先设计的布局加载到对话框中。我将发布一段代码。

Button login = (Button) findViewById(R.id.btn_login);

login.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(getApplication());

dialog.setContentView(R.layout.journey_details);
dialog.setTitle("Android Custom Dialog Box");

Button dialogButton = (Button) dialog.findViewById(R.id.btn_start_jrny);

dialogButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});

dialog.show();

}
});

并且它在日志猫中显示以下错误

     E/AndroidRuntime(1412): FATAL EXCEPTION: main
E/AndroidRuntime(1412): Process: com.xont.geotracker, PID: 1412
E/AndroidRuntime(1412): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
E/AndroidRuntime(1412): at android.view.ViewRootImpl.setView(ViewRootImpl.java:538)
E/AndroidRuntime(1412): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
E/AndroidRuntime(1412): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
E/AndroidRuntime(1412): at android.app.Dialog.show(Dialog.java:286)
E/AndroidRuntime(1412): at com.xont.geotracker.Loging$1.onClick(Loging.java:61)
E/AndroidRuntime(1412): at android.view.View.performClick(View.java:4424)
E/AndroidRuntime(1412): at android.view.View$PerformClick.run(View.java:18383)
E/AndroidRuntime(1412): at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime(1412): at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(1412): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1412): at android.app.ActivityThread.main(ActivityThread.java:4998)
E/AndroidRuntime(1412): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1412): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1412): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
E/AndroidRuntime(1412): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
E/AndroidRuntime(1412): at dalvik.system.NativeStart.main(Native Method)

有人可以帮我找出错误吗?需要帮忙。谢谢!

最佳答案

改变

final Dialog dialog = new Dialog(getApplication());

final Dialog dialog = new Dialog(YourActivity.this);

如果您在 Fragment 内部,请更改为

final Dialog dialog = new Dialog(getActivity());

Dialog 需要一个窗口标记不为 null 的 Context 引用。这里 ApplicationContext 的窗口标记为 null,而 Activity 将拥有自己的窗口

关于java - Android自定义对话框报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20779377/

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