如何在AlertDialog的布局中添加自定义按钮?

Pep*_*tal 23 layout android dialog button android-alertdialog

我有AlertDialog有正面和负面按钮.在AlertDialog布局中,我有EditText和两个按钮(btnAdd1,btnAdd2).我希望当用户点击Button btnAdd1或btnAdd2时,将相同的文本添加到AlertDialog中的EditText(但没有关闭AlertDialog).这可能是在AlertDialog中做的还是我只能使用Dialog?

这是AlertDialog的布局(R.layout.prompt):

<LinearLayout>
<EditText
    android:id="@+id/userInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="text" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/btnAdd1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="bla" />

<Button
    android:id="@+id/btnAdd2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="bla" />

  </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

这是源代码:

    LayoutInflater layoutInflater = LayoutInflater.from(this);
        View promptView = layoutInflater.inflate(R.layout.prompt, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setView(promptView);
    alertDialogBuilder
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                              //...

                }
            })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });

    AlertDialog alertD = alertDialogBuilder.create();
    alertD.show();
Run Code Online (Sandbox Code Playgroud)

我想从布局中访问btnAdd1和btnAdd2.将OnClickListener()设置为这两个按钮.

Vik*_*ram 41

以下代码将从视图中提取R.layout.prompt并将其设置为AlertDialog.在positive和negative按钮将无法使用.您可以设置onClick为行为btnAdd1和btnAdd2:

LayoutInflater layoutInflater = LayoutInflater.from(this);
View promptView = layoutInflater.inflate(R.layout.prompt, null);

final AlertDialog alertD = new AlertDialog.Builder(this).create();

EditText userInput = (EditText) promptView.findViewById(R.id.userInput);

Button btnAdd1 = (Button) promptView.findViewById(R.id.btnAdd1);

Button btnAdd2 = (Button) promptView.findViewById(R.id.btnAdd2);

btnAdd1.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

        // btnAdd1 has been clicked

    }
});

btnAdd2.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

        // btnAdd2 has been clicked

    }
});

alertD.setView(promptView);

alertD.show();
Run Code Online (Sandbox Code Playgroud)