2014-12-21 38 views
0

當我創建一個對話框並在按鈕上設置onClickListener時,應用程序崩潰。相同的代碼在另一個活動中起作用,那麼情況如何?Android對話框Button.setonClickListener

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    initNewUserDialog(); 
    initNewLocationDialog(); 

...

private void initNewLocationDialog() { 
    new_location_Dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen); 
    setContentView(R.layout.new_location); 
    new_location_Button = (Button)new_location_Dialog.findViewById(R.id.newlocation_ok); 
    //Crash here 
    new_location_Button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      new_location_Dialog.dismiss(); 
     } 
    }); 
    new_location_editText = (EditText)new_location_Dialog.findViewById(R.id.newlocation_edittext); 
    new_location_Dialog.hide(); 
} 
+0

logcat的嘗試,請... –

+0

錯誤是空指針異常? – Mou

+2

爲什麼你有另一個'setContentView(R.layout.new_location);'? –

回答

1

如果你想給你的對話框的自定義佈局,你應該對話框本身

dialog.setContentView(....); 

但是它最好使上調用的setContentView()你自定義對話框並在構造器中設置您的佈局

public class MyDialog extends Dialog { 

public MyDialog(Context context) { 
    super(context, R.style.your_layout); 
} 
} 

檢查這個構造:

Dialog(Context context, int theme) 

見:http://developer.android.com/reference/android/app/Dialog.html

+0

噢,我忘記了dialog.setcontentview ...謝謝! – shizzle31

0

您可能會檢查this教程。

從那裏我將與

final Dialog new_location_Dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen); 
    new_location_Dialog.setContentView(R.layout.new_location);