Show dialog only using Context instead of Activity instance(仅使用 Context 而不是 Activity 实例显示对话框)
问题描述
如果我使用 Activity 实例,我可以显示对话框,但是当我使用 Context 或 Application Context 实例时,对话框没有显示.
I could show dialog if I uses an Activity instance but when I uses Context or Application Context instance Dialog is not showing.
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMessage(msg);
if (null != positiveLabel) {
builder.setPositiveButton(positiveLabel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
if (null != listener) {
listener.onOk();
}
}
});
}
if (null != negativeLable) {
builder.setNegativeButton(negativeLable, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
if (null != listener) {
listener.onCancel();
}
}
});
}
builder.create().show();
你能不能给我一个解决方案来显示对话框而不使用 Activity 实例
Can you please give me a solution to show dialog without using Activity instance
推荐答案
这个问题也是我最近遇到的问题,没有Activity实例就不能创建对话框.getApplicationContext() 调用也不起作用.我这样做的方法是从一个活动调用创建对话框的方法,并传递this",即对该活动的引用作为参数.
The problem is something I faced recently too, you cant create a dialog without and activity instance. getApplicationContext() call doesn't work too. The way I did this is to make the call to a method that creates the dialog, from an activity, and pass "this" i.e. the reference to that activity as a parameter.
如果您打算重用此代码,作为可重用组件或作为在多个位置创建对话框的机制,请创建一个基本活动类并在其中包含此方法,并根据需要在子类活动中使用它.
If you are going to reuse this code, as a reusable component or as a mechanism to create dialogs at multiple places, create a base activity class and have this method in there, and use it in sub-classed activities as needed.
这篇关于仅使用 Context 而不是 Activity 实例显示对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:仅使用 Context 而不是 Activity 实例显示对话框


- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01