JuniorIncanter
JuniorIncanter

Reputation: 1579

Android App: Replace default button background with custom background in a Dialog Fragment

What I'm trying to do is change the default backgrounds of a custom DialogFragment that I have written. Normally, I would do this by changing the XML layout file, however, for a DialogFragment these buttons don't exist in the layout file.

In essence, I'm trying to get access to the setPositiveButton, setNegativeButton and setNeutral buttons in order to modify them. Alternatively, I would next try to do this by getting them by id, however, since they aren't defined in a layout file, I do not have a corresponding id for them. I've found plenty examples of how to modify the rest of the layout, but I can't find anywhere that positive/neutral/negative buttons are modifiable.

Ideally, I could do this in the following block of code:

.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int id) {
                       ...
                   }
               })

Thanks in advance.

Upvotes: 0

Views: 1504

Answers (1)

Libin
Libin

Reputation: 17095

Here is the code ... The button instance is valid only after the dialog created. Hope this helps you.

public static class CustomDialog extends DialogFragment
{

    public static CustomDialog newInstance()
    {
        return new CustomDialog();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        super.onCreateDialog(savedInstanceState);
        Builder builder = new AlertDialog.Builder(getActivity());

        AlertDialog dialog = builder.create();

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK",new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {


            }
        });

        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL",new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {


            }
        });


        return dialog;

    }

    @Override
    public void onStart()
    {
        super.onStart();
        Button pButton =  ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
        Button nButton =  ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEGATIVE);

        pButton.setBackgroundColor(getResources().getColor(R.color.Blue));
        nButton.setBackgroundColor(getResources().getColor(R.color.Green));
    }
}

Upvotes: 5

Related Questions