创建对话框并在按钮上设置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();
}
最佳答案
如果要为对话框提供自定义布局,则应在对话框本身上调用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
关于java - Android对话框Button.setonClickListener,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27592044/