Android Show Dialog不能仅在屏幕上淡出

时间:2016-06-30 13:36:02

标签: android

我试图从一个带有单选项选择列表的片段调用一个对话框窗口,但是当我点击该按钮时,只有屏幕淡出没有任何显示...

通话功能:

private void showDialog() {
    myDialog dialog = new myDialog();
    dialog.show(getActivity().getSupportFragmentManager(),"dialog");
}

对话类:

public class Dialog extends DialogFragment {

    final String[] items= {"item 1","item 2","item 3"};
    String selection;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Choose One").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case 0:
                        selection = items[which];
                        break;
                    case 1:
                        selection = items[which];
                        break;
                    case 2:
                        selection = items[which];
                        break;
                    default:
                        break;
                }
            }
        }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "item selected: " + selection, Toast.LENGTH_SHORT).show();
            }
        });
        return super.onCreateDialog(savedInstanceState);
    }
}

2 个答案:

答案 0 :(得分:2)

onCreateDialog中,您应该返回您创建的Dialog

public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Choose One").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case 0:
                    selection = items[which];
                    break;
                case 1:
                    selection = items[which];
                    break;
                case 2:
                    selection = items[which];
                    break;
                default:
                    break;
            }
        }
    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getActivity(), "item selected: " + selection, Toast.LENGTH_SHORT).show();
        }
    });
    return builder.create();
}

将您的班级Dialog重命名为CustomDialog或类似名称,因为它已被使用 你可以展示它:

private void showDialog() {
    CustomDialog dialog = new CustomDialog();
    dialog.show(getActivity().getSupportFragmentManager(),"dialog");
}

答案 1 :(得分:1)

不要返回super.onCreateDialog(savedInstanceState),而是返回builder.create()