Android app: replace the default button background with the custom background in the dialog fragment

What I'm trying to do is change the default background for the custom DialogFragment dialog that I wrote. I usually do this by modifying the XML layout file, however for DialogFragment these buttons do not exist in the layout file.

In essence, I'm trying to access the setPositiveButton, setNegativeButton, and setNeutral buttons to modify them. Alternatively, I would try to do this by getting them by id, however, since they are not defined in the layout file, I do not have the corresponding identifier for them. I found many examples of how to change the rest of the layout, but I can not find anywhere that the buttons with positive / neutral / negative can be modified.

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.

0
source share
1 answer

Here is the code ... The button instance is valid only after creating the dialog. 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));
    }
}
+5
source

Source: https://habr.com/ru/post/1548022/


All Articles