Home > database >  how to change color of buttons in dialog fragment
how to change color of buttons in dialog fragment

Time:12-21

I have this class java:

public class DatePickerFragment extends DialogFragment {
    private Calendar date;

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        DatePicker datePicker = new DatePicker(getActivity());
        date = Calendar.getInstance();

        return new AlertDialog.Builder(getActivity())
                .setView(datePicker)
                .setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                date.set(Calendar.YEAR, datePicker.getYear());
                                date.set(Calendar.MONDAY, datePicker.getMonth());
                                date.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());


                                ((SigninActivity)getActivity()).doPositiveClick(date);
                            }
                        }
                        
                )

                .setNegativeButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dismiss();
                    }
                })

                .create()
                ;
        
    }

I would like to change the color of the two buttons "ok" and "back". As color it takes the one in the themes.xml file, the colorPrimary, but I don't understand where to change this setting.

I don't want to change the colorPrimary because I just need to customize the two buttons.

Here instead is where I call the datepicker to set the date:

data.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        new DatePickerFragment().show(getSupportFragmentManager(), DatePickerFragment.TAG);

    }
});

CodePudding user response:

You can change button colors by doing this in onStart():

public void onStart() {
    super.onStart();
    ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.GREEN);
    ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED);
}
  • Related