2010-05-01 81 views
4

所以這與我之前問過的問題有關。我正在嘗試使用指定的佈局顯示警報。我的佈局是:帶自定義佈局失敗的警報對話框

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:id="@+id/layout_root" 
       android:orientation="horizontal" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:padding="10dp"> 
    <TextView android:id="@+id/text" 
       android:layout_width="wrap_content" 
       android:layout_height="fill_parent" 
       android:textColor="#FFF" /> 
</LinearLayout> 

和代碼來調用並顯示警告對話框:

Context mContext = getApplicationContext(); 

    AlertDialog.Builder builder = new AlertDialog.Builder(mContext); 
    // use a custom View defined in xml 
    View view = LayoutInflater.from(mContext).inflate(R.layout.sell_dialog,  (ViewGroup) findViewById(R.id.layout_root)); 
    builder.setView(view); 
    builder.setPositiveButton(android.R.string.ok, new OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 

      // do whatever you want with the input 
     } 
    }); 
    AlertDialog alertDialog = builder.create(); 

    alertDialog.show(); 

當我運行它,我得到一個錯誤說:

未捕獲的處理程序:螺紋主力退出由於未捕獲的異常 android.view.WindowManager $ NadTokenException:無法添加窗口 - 標記null不適用於應用程序

我已經通過a ndroid開發網站,並無法弄清楚。我想我只是錯過了一些顯而易見的東西,但修復並沒有跳出我的身邊。我怎樣才能讓這個警報對話框顯示?

回答

9

請勿使用getApplicationContext()。該方法僅適用於Context(例如,Activity) - 使用Context作爲AlertDialog.Builder

Here is a sample project從我的一本書中,除其他外,顯示基於自定義ViewAlertDialog

+0

工作就像一個魅力。非常感謝! – cmptrer 2010-05-01 04:11:55

+0

我對使用自定義視圖的警報對話框的示例感興趣,但是您的鏈接沒有此類示例。 – Nemi 2010-08-09 01:40:35

+0

@Nemi:哎呀,你說得對。對於那個很抱歉。試試這個:http://github.com/commonsguy/cwac-colormixer – CommonsWare 2010-08-09 11:53:30