Cumulations Logo

Every app that is launched/yet to be launched will be having its own theme based on its branding. Most of the developers miss out on maintaining color uniformity throughout the app. This is mainly because of dialogs/popups and toast messages. Even though Android supports applying different styles to dialog it's not much extensible and also requires an extra bit of coding. We have seen a lot of open source libraries which helps us in styling dialogs (and also for toasts). Sometimes we may have to re-organize dialog content as well along with styling and we can't expect open source libs to help us in achieving this. After spending some time in StackOverflow I found out a solution where we can set the view as a content for the AlertDialog builder like below:

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    LayoutInflater inflater = getActivity().getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.dialog_layout, null));

The above code didn't work as expected, it leaves few pixels gap at the top and bottom. I would any day prefer Android style than using the above code to customize my dialog which makes it ugly.

After digging through AOSP code I found out a solution where creating plain Dialog instance and calling setContentView for the same helped me achieve what I wanted. Below is the code snippet which you can use to set your own layout XML for styling the dialogs:

     LinearLayout view = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.dialog_layout, null);
     final EditText someView = (EditText) view.findViewById(R.id.some_text);

     final Dialog dialog = new Dialog(this);
     dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);

     // positive button which is part of inflated layout
     view.findViewById(R.id.done).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        dialog.cancel();
        // do something
      }
     });

     // negative button which is part of inflated layout
     view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        dialog.cancel();
      }
     });

     dialog.setContentView(view);
     dialog.show();

Don't forget to call

dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);

or else you will face runtime exception with the message:

requestFeature() must be called before adding content.