How can can I add custom buttons into an AlertDialog's layout?

The following code will inflate a view from R.layout.prompt and set it to the AlertDialog. The positive and negative buttons will not be used. You can set the onClick behaviors for btnAdd1 and 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();

what you want to do is;

alertD.show();
Button button = (Button)promptView.findViewById(R.id.buttonId);
button.setOnClickListener(....)

using the view to call findViewById, rather than the activity, which will look for the id in the layout that is being displayed.


According to this approach i am able to create the image button but if i want to dismiss or cancel dialog on Cancel button then what i have to do..

public static void alertDialogShow(final Context context,
            final String resultMobile) {

        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.prompt,
                null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        // set prompts.xml to alertdialog builder
        alertDialogBuilder.setView(promptsView);
        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.editTextDialogUserInput);
        userInput.setText(resultMobile);
        userInput.setEnabled(false);
btnCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

            }
        });