Search code examples
androidbuttoncolorsandroid-dialogfragment

Android: how to change color to buttons of AlertDialogFragment


I can't find the way to specify a custom text color to the buttons of the AlertDialogFragment.

I have tried with theme and programmatically, but no luck.


Solution

  • I have a DialogFragment, in which I show an AlertDialog

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    
    builder.setView(inflater.inflate(R.layout.my_dialog, null))
    .setPositiveButton(R.string.open_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                ...
            }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                ...
            }
        });
    ...
    connDialog = builder.create();
    connDialog.setOnShowListener(new DialogInterface.OnShowListener() {
    
            @Override
            public void onShow(DialogInterface dialog) {
                Button b = connDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                b.setTextColor(getActivity().getResources().getColor(R.color.white));
                b.setBackgroundColor(getActivity().getResources().getColor(R.color.black));
                ...
            }
        });
    

    Setting them in AlertDialog's builder didn't help me, either. Try this way.