仅使用上下文而不是活动实例显示对话框 [英] Show dialog only using Context instead of Activity instance
问题描述
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对话框,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实例
这个问题是我最近面临的问题,你不能创建一个没有和活动实例的对话框。 getApplicationContext()调用也不起作用。我这样做的方法是调用一个方法,从一个活动中创建对话框,并传递this,即对该活动的引用作为参数。
如果要重用此代码,作为可重用组件或在多个场所创建对话框的机制,请创建一个基本活动类并在其中使用此方法,并根据需要在子类活动中使用它。 / p>
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();
Can you please give me a solution to show dialog without using Activity instance
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.
这篇关于仅使用上下文而不是活动实例显示对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!