Android Dialog Button.setonClickListener

时间:2014-12-21 17:46:48

标签: java android

当我创建一个对话框并在按钮上设置onClickListener时,应用程序崩溃了。相同的代码在另一个Activity中有效,那有什么关系呢?

@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();
}

2 个答案:

答案 0 :(得分:1)

如果你想给对话框一个自定义布局,你应该在对话框本身上调用setContentView()

dialog.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

答案 1 :(得分: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);