当我点击“保存”或“取消”按钮时,我想忽略此布局,但我不能。 dialog.dismiss或dialog.cancel将无法正常工作。单击“保存”按钮时,它将起作用,但之后使用.close或.dismiss行将不会关闭布局。这是我的代码。
private Dialog getAddDialog() {
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.addLesson,null);
Button save= (Button) layout.findViewById(R.id.btnSave);
Button cancel= (Button) layout.findViewById(R.id.btnCancel);
final EditText answer = (EditText) layout.findViewById(R.id.et);
final Spinner sp = (Spinner) layout.findViewById(R.id.sp);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.lessons, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
final DatePicker datePicker = (DatePicker) layout.findViewById(R.id.dp);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add information");
builder.setView(layout);
final AlertDialog dialog = builder.create();
builder.show();
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
int day= datePicker.getDayOfMonth();
int month= datePicker.getMonth()+1;
int year= datePicker.getYear();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = null;
try {
date = df.parse(day+"/"+month+"/"+year);
} catch (ParseException e) {
e.printStackTrace();
}
long date= date.getTime();
int position= sp.getSelectedItemPosition();
String lesson= (String) sp.getItemAtPosition(position);
int lessonNumber= Integer.valueOf(answer.getText().toString());
Student student= new Student (lesson,lessonNumber,date);
Database db = new Database (getApplicationContext());
long id = db.AddInfo(student);
if (id==-1){
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Successful", Toast.LENGTH_SHORT).show();
}
getList();
} catch (NumberFormatException e) {
Toast.makeText(MainActivity.this, "Please enter the number", Toast.LENGTH_SHORT).show();
}
dialog.dismiss(); // <-- DOESN'T WORK
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
dialog.dismiss(); // <-- DOESN'T WORK
} catch (Exception e) {
Toast.makeText(MainActivity.this, "" +e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
});
return dialog;
}
答案 0 :(得分:1)
删除此行
builder.show();
对于我来说,包括这一行,是强制关闭应用程序。但删除后,它工作正常,甚至单击按钮后对话框被解除。
Dialog
应为show()
而不是Builder