Android

Customizing dialog in Android

Pradeep V R

25 Jan 2015

Customizing dialog in Android

Every app that is launched/yet to be launched will be having its own theme based on its branding. Let’s understand how customizing dialog in Android works. 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 muchly extensible and also requires an extra bit of coding. We have seen a lot of open-source libraries which help 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 a solution where we can set the view as content for the AlertDialog builder like the below:

customizing dialog in Android

 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 a 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 a solution where creating a 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 a runtime exception with the message:

requestFeature() must be called before adding content.

 

Also, read:

How AI Can Be Beneficial to Healthcare Mobile apps?
Complete Guide to Kotlin For Android App Development