如何将逻辑放在对话框中?还是做动态对话?

时间:2018-05-27 09:36:57

标签: android dialog alertdialog

我有这个对话框,允许用户选择一些复选框和微调器,以自定义项目。

如果我在 //计算自定义的行中添加逻辑,我可以在用户按下保存后计算选项。

但我想在对话框打开时计算选项,并在对话框打开时显示动态文本。这可能吗?或者我该怎么做?

btnCustomize.setOnClickListener(new View.OnClickListener(){
    @Override public void onClick(View v){
        AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext(), R.style.CustomDialogTheme);
        builder.setTitle("Customize");
        final View view = inflater.inflate(R.layout.popup_customize, null);
        builder.setView(view);
        builder.setPositiveButton("Save", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                // User clicked OK button
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                // User cancelled the dialog
            }
        });
        final AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener(){
            @Override public void onClick(View v){
                // calculation customization here, after user clicks "Save"
                dialog.dismiss();
            }
        });
    }
});

1 个答案:

答案 0 :(得分:0)

最简单和最好的方法是使用DialogFragment,您可以定义每个对象并进行更改,例如:

public class CustomDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.CustomDialog2);
    LayoutInflater inflater = getActivity().getLayoutInflater();

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.activity_main,null ));
            // Add action buttons

    Dialog dialog = builder.create();
    return dialog;
}  }

并在活动中创建并调用它:

CustomDialog dialog=new CustomDialog();
dialog.show(getFragmentManager(),"tag");