問題描述
如果我使用 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 實例顯示對話框的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!