user3673449
user3673449

Reputation: 357

Customize alert dialog

I have a fragment, that automatically shows a dialog. I want to change the color of the dialog's title and the color of the buttons (when pressed). Is there any way I can do that?

public class MyFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        //...
        AlertDialog ad = new AlertDialog.Builder(getActivity()).setTitle("Title")
                .setMessage("Message")
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        //YES logic
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
            //NO logic}
        }).create();
            ad.show();
            inflater.inflate(R.layout.fragment_my, container);
            return super.onCreateView(inflater, container, savedInstanceState);
    }

Upvotes: 0

Views: 2040

Answers (1)

frogatto
frogatto

Reputation: 29285

You can create your own Dialog class which extends Android Dialog, then you can customize its background drawable, customize its title and so on.

public class MyDialog extends Dialog {

    public MyDialog(Context context) {
        // Adding your custom theme to it
        super(context, R.style.mydialog_theme);
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Removing its original title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Getting reference to its window object
        Window window = getWindow();

        // Where in the screen your dialog pops up
        window.setGravity(Gravity.CENTER);

        // Setting its content view 
        setContentView(R.layout.mydialog_layout);
    }
}

As a result you can create such a dialog like this:
enter image description here

Upvotes: 1

Related Questions