Tôi có một đơn giản AlertDialog
hiển thị danh sách một số mục và sau khi nhấp vào một trong số chúng, mục được nhấp sẽ được chuyển trở lại kèm theo Activity
. Tôi cũng muốn thực hiện một số xử lý mặc định khi người dùng hủy hộp thoại (bằng cách sử dụng nút quay lại ) - cụ thể hơn, tôi muốn chuyển một chuỗi trống đến hoạt động trong trường hợp này.OnCancelListener không được gọi trong Hộp thoại
Tuy nhiên, nếu tôi đặt hộp thoại trong một DialogFragment
(từ gói tương thích), các OnCancelListener
không được gọi khi tôi đóng hộp thoại với nút quay lại. Tôi đang làm gì sai?
public class SelectItemDialog extends DialogFragment {
public interface Callback {
void onItemSelected(String string);
}
private static final String ARG_ITEMS = "items";
private Callback callback;
public static SelectItemDialog fromItems(Collection<String> items) {
SelectItemDialog fragment = new SelectItemDialog();
fragment.setArguments(newArguments(items));
return fragment;
}
private static Bundle newArguments(Collection<String> items) {
Bundle arguments = new Bundle();
arguments.putStringArray(ARG_ITEMS, items.toArray(new String[items.size()]));
return arguments;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback = (Callback) activity;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] items = getArguments().getStringArray(ARG_ITEMS);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.dialog_select_email_title)
.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
callback.onItemSelected(items[which]);
}
})
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// this code is not executed
callback.onItemSelected("");
throw new RuntimeException("dialog cancelled");
}
})
.create();
}
}
tôi thay đổi nội dung câu hỏi của tôi. Tôi muốn mã trong 'OnCancelListener' được gọi khi hộp thoại được đóng lại với nút * quay lại *. – Natix
@Natix xem [câu trả lời này] (http://stackoverflow.com/a/7815342/1815485), nó đang làm điều tương tự. Bạn phải thêm một 'OnKeyListener' để xem cho việc bấm phím trở lại. –
Vâng, giải pháp này có thể hoạt động, nhưng nếu tôi tạo hộp thoại trực tiếp bên trong một hoạt động mà không có 'DialogFragment', thì 'OnCancelListener' được gọi - cả khi nút quay lại được nhấn hoặc nếu người dùng nhấp vào bên ngoài hộp thoại. Tôi không hiểu tại sao 'DialogFragment' thay đổi hành vi. – Natix