我不知道如何在自定义对话框中引用某个项目。我看过here,here,here和其他地方。 我无法在自定义对话框中获取要在onclick事件中引用的复选框,或者当我尝试直接在onClick 上的正按钮中调用它时。
XML:
<TextView
android:id="@+id/dialog_title"
style="?android:attr/textAppearanceLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/White"
android:layout_weight="1"
android:text="@string/delete_db_on_exit"
android:textColor="@color/Black" />
<TextView
android:id="@+id/dialog_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/White"
android:text="@string/confirm_delete"
android:textColor="@color/Black" />
<CheckBox
android:id="@+id/confirm_delete_checkbox"
android:paddingTop="5dp"
android:background="@color/White"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/confirm_delete_checkbox"/>
调用对话框的Activity中的代码:
private LayoutInflater inflator;
private View dialogView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_administration);
inflator = this.getLayoutInflater();
dialogView = inflator.inflate(R.layout.custom_dialog, null);
}
public void deleteDatabases(View view){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this)
.setTitle(R.string.delete_db_on_exit)
.setCustomTitle(getLayoutInflater().inflate(R.layout.custom_dialog, null))
.setPositiveButton(R.string.confirm_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if (((CheckBox) dialogView.findViewById(R.id.confirm_delete_checkbox)).isChecked()) { //Never true. No exceptions thrown
setDeleteDatabaseOnExit();
dialog.cancel();
//Navigate back to main activity
Intent mainActivityIntent = new Intent(AdministrationActivity.this, MainActivity.class);
startActivityForResult(mainActivityIntent, 1);
}
}
});
CheckBox confirmDeleteCheckbox = (CheckBox)dialogView.findViewById(R.id.confirm_delete_checkbox);
confirmDeleteCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int x = 0;
x = 1;
}
});
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
答案 0 :(得分:0)
变化:
.setCustomTitle(getLayoutInflater().inflate(R.layout.custom_dialog, null))
为:
.setCustomTitle(dialogView)
在您的对话框中,您正在创建一个新的custom_dialog视图,该视图也有一个复选框,但与dialogView
中的复选框不同。这就是为什么当你检查它是真的时,对话框中的那个是自己为true但是dialogView中的那个仍然是假的。