java - 如何将多个功能添加到一个命令中?

标签 java android

我有一个带有 EditText 输入字段的对话框窗口。我想多次使用输入值,但希望代码尽可能少。目前,我必须为每次单击按钮设置新的 alertdialogBu​​ilder,但这不是很灵活。

我将该代码用于我的 alertDialogBu​​ilder

public static void makeEditTextInputDialog(String caption, final Context mContext){
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View inputDialogView = inflater.inflate(R.layout.dialog_input_edittext, null);

   AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setView(inputDialogView);

        final EditText etInput = (EditText) inputDialogView.findViewById(R.id.et_inputdialog);
        final TextView tvCaption = (TextView) inputDialogView.findViewById(R.id.tv_inputdialog_caption);

        tvCaption.setText(caption);

        builder .setCancelable(true)
                .setPositiveButton(R.string.apply, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

我需要如何设置我的类或函数,以便我可以创建一个函数,我可以在其中添加更多带有点的函数

:makeInputDialog(caption,context).newFunction(param).changeTheTextOfAnotherTextView(desiredTextView);

最佳答案

您应该能够做到这一点,方法是让每个方法都返回 this 作为您正在创建的 Builder 类的实例。这样您就可以将调用与“.”链接在一起。

这是一个简单的例子:

class MessageBuilder {
    String address = "unknown";
    String state = "unknown";
    String country = "unknown";

    MessageBuilder() {}


    String show() {
        return address + ", " + state + ", " + country;
    }

    MessageBuilder setAddress(String address) {
        this.address = address;
        return this;
    }

    MessageBuilder setState(String state) {
        this.state = state;
        return this;
    }

    MessageBuilder setCountry(String country) {
        this.country = country;
        return this;
    }
}

您可以通过将 set 方法链接在一起来使用它:

    MessageBuilder builder = new MessageBuilder();
    String msg = builder.setState("CA").setAddress("123 Main St.").show();
    Log.d("MessageBuilder", msg);

...在日志中产生这个:

09-24 14:25:16.254 {...}  D/MessageBuilder: 123 Main St., CA, unknown

关于java - 如何将多个功能添加到一个命令中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46392815/

相关文章:

java - 使用 Cargo 和 Maven 远程部署 WAR,无需 HOT 部署

java - 这个java代码背后的逻辑是什么

java - 比较搜索中的 SimpleStringProperty

android - 模块的依赖项详细信息多次显示相同的依赖项

java - 如何在 Android 中借助 DTO 解析此内容

android - 我如何使用内容提供程序访问另一个应用程序中的一个应用程序的数据

android - Gradle - 仅执行单一构建类型

java - 我们可以假设 x == (int)sqrt(x * x) 对于所有正整数吗?

java - 使用 JSOUP 从另一个网站获取数据

android - 在服务器端验证应用程序是否是我的