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

梦想的初衷 提交于 2019-12-25 01:49:59

问题


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.


回答1:


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));
    }
}


来源:https://stackoverflow.com/questions/20389663/android-app-replace-default-button-background-with-custom-background-in-a-dialo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!