2011-04-04 235 views
5

我試圖在tutorial on the Android developer site之後創建自定義對話框,但每次嘗試顯示對話框時都會崩潰。這裏是我的代碼:Android自定義對話框

Context mContext = getApplicationContext(); 
Dialog dialog = new Dialog(mContext); 

dialog.setContentView(R.layout.custom_dialog); 
dialog.setTitle("Custom Dialog"); 
dialog.show(); 

而且這裏是我的佈局XML:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    android:id="@+id/layout_root" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:padding="10dp" 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
    <Button 
     android:id="@+id/btnConfirm" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Add text" 
     android:layout_below="@+id/txtNewText" 
     android:layout_alignParentLeft="true"> 
    </Button> 
    <EditText 
     android:id="@+id/txtNewText" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:textSize="18sp" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentLeft="true"> 
    </EditText> 
</RelativeLayout> 
+4

你能提供的錯誤日誌? – MByD 2011-04-04 21:13:49

回答

8

考慮模式:

private static final int MY_DIALOG= 0; 

protected Dialog onCreateDialog(int id) { 
    Dialog dialog; 
    switch(id) { 
     case MY_DIALOG: 
      dialog= getInstanceMyDialog(); 
      break; 
     default: 
      dialog = null; 
    } 
    return dialog; 
} 

private Dialog getInstanceMyDialog() { 
    final Dialog d= new Dialog(this); //<=====THIS 
    d.setContentView(R.layout.custom_dialog); 
    d.setTitle("Custom Dialog"); 
    return d; 
} 

JAL

+0

我不明白.. – Elec0 2011-04-04 23:46:15

+0

@ElecO您提供的鏈接使用此模式創建自定義對話框。最大的區別是,本教程調用showDialog(MY_DIALOG),而您發佈的代碼使用dialog.show()。我的工作代碼是:http://sites.google.com/site/jalcomputing/home/mac-osx-android-programming-tutorial/custom-password-dialog – JAL 2011-04-05 04:22:00

3

這爲我工作: problem-creating-a-custom-dialog

使用這個代替getApplicationContext的實例對話框時,():

Dialog dialog = new Dialog(this); 
+0

爲什麼會發生這種情況?有時我想在點擊一個按鈕後顯示一個對話框。如果我使用「this」而不是「getApplicationContext()」不起作用,因爲「this」引用了「OnClickListener」。我必須做一些醜陋的解決方法來使用「this」... – ffleandro 2012-02-13 16:28:35

+0

不,你不只是寫ClassName.this的類應該是這個 – endryha 2012-03-28 14:15:20