2011-10-13 110 views
2

我想創建一個類,我可以調用時需要顯示帶有參數和兒子的AlertDialog。使用Android AlertDialog

問題是我不知道該類是否必須是一個活動... alertDialog需要一個上下文,但我可以發送當前的一個,因爲我想要的是顯示實際活動的警報(不是創建一個新的,我想在實際屏幕上顯示警報)。但我無法得到它。我得到的錯誤發送的實際活動的上下文...

只有當我創建類像一個活動,但我的工作,但與此,alertDialog單獨出現沒有實際的屏幕後面。

我該怎麼辦?我不知道我的理解上下文...

感謝

+0

什麼代碼給你錯誤發送實際上下文時? –

回答

1

你的課不需要擴展任何東西來產生對話框。你可以試試這種方式來產生一個靜態方法,爲你創建一個對話框。 確保當你打電話給你用這個,而不是getApplicationContext(你的方法)

MyDialogClass.getDialog(this); //good! 
MyDialogClass.getDialog(getApplicationContext()); //results in error 

這可能是你錯誤的原因

Example類:

public class MyDialogClass 
{ 
public static AlertDialog getDialog(Context context) 
    { 
     Builder builder = new Builder(context); 
     builder.setTitle("Title").setMessage("Msg").setCancelable(false) 
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) 
        { 


        } 
       }).setNegativeButton("No", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) 
        { 

        } 
       }); 
     return builder.create(); 
    } 
} 
+0

真的非常感謝!這就是我需要的!另外,我還有一個簡單的問題:我可以從一個活動以外的string.xml獲取一些數據嗎?我收到一個錯誤。再次感謝man :)) – Frion3L

+0

只要你能夠通過context.getString(R.string.your_resource)訪問上下文,你應該可以。如果這沒有成功,可能是因爲我上面提到的上下文來自getApplicationContext()而不是這個。您能否告訴我們您嘗試檢索該值時遇到的錯誤? – dymmeh

+0

@dymmeh我沒有使用任何上下文。我認爲獲取字符串的服務並不取決於Activity ...因此,如果它只與Activity一起使用,也許我必須創建另一個解決方案,因爲我需要諮詢它以處理許多非活動類 – FrioneL

0

AynscTask不需要Context;不,它不需要是一項活動。 http://developer.android.com/reference/android/os/AsyncTask.html

無論如何,你應該能夠在沒有問題的情況下隨時獲得上下文。只是這樣做:

public class MyApplication extends Application{ 

    private static Context context; 

    public void onCreate(){ 
     super.onCreate(); 
     context = getApplicationContext(); 
    } 

    public static Context getAppContext() { 
     return context; 
    } 
} 

然後你可以從任何你想要與MyApplication.getAppContext();的情況,以及通過它,它應該工作。