Android DialogFragment - MultiChoice对话框复选框不会更新/需要两次单击

时间:2017-03-21 23:13:59

标签: android android-dialogfragment android-dialog

我认为这只是在最近的Android API中才开始发生,但问题是,当您第一次尝试在MultiChoice对话框中选中一个复选框时,需要额外点击才能更新UI。

我很确定这是因为我的代码非常简单而导致Android错误。

经过大量的实验,我找到了答案,所以将在下面分享......

1 个答案:

答案 0 :(得分:0)

解决方案的棘手部分是获取View对象。获得View后,您可以invalidate()来更新复选框的用户界面。

以下是DialogFragment子类的基本要点:

public class MyMultiChoiceDialogFragment extends DialogFragment {

    private View mView = null;

    @Override @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(title);
        builder.setMultiChoiceItems(
            cursor,
            isCheckedColumn
            labelColumn
            new DialogInterface.OnMultiChoiceClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {

                // Handle the checkbox de/selection

                /*
                 * The problem is that, despite onClick being called (with the correct parameter values), the
                 * checkbox ticks were not updating on the UI.
                 * Solution is to invalidate/redraw the layout so the checkboxes also update visually
                 */
                mView.invalidate();
                mView.forceLayout(); // Following tests, this line is also required.

            }
        });

        AlertDialog dialog = builder.create();

        /*
         * This seems to be the only way to get the view.
         * Save it in an instance variable so we can access it within onClick()
         */
        mView = dialog.getListView();

        return dialog;
    }    

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mView = null; // Clean up / prevent memory leak - necessary?
    }

}