Android custom themed Dialog – Tutorial

Posted by

Introduction

I was trying to create dialogs and alert dialogs that look the same on all Android smartphones, when I realized that different types of smart phones do something different with the default themes and make buttons, dialogs, etc. look very different from one phone to the other. Everything looks very different in the simulator than it does on a Droid X or Droid 2 for example. Things look more similar on a Samsung Galaxy S, or HTC Incredible, but even there you can see some differences.

Removing all themes

Since each phone manufacturer can change the default themes that come with Android, it makes sense to start with a theme of no-theme, and work up from there. Here’s the first step in creating a dialog that looks the same on all phones:

Dialog dialog = new Dialog(ctx, android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(enclosedView);
return dialog;

This will create a dialog screen which is completely transparent,and has no labels, or titles, or background colors.

Assembling the no-theme dialog

Now that the dialog is empty, it is time to start adding things to it. The following diagram depicts the order in which views need to be added to this empty dialog.

  1. The background of the dialog must be set, this can be done by specifying a color, or a nine patch, or a PNG. This can be a semi transparent image, which is tiled for the entire device screen area and acts as a veil for the LinearLayout.
  2. The LinearLayout view must then be added to the dialog. The background of this view must be set as well. This background is what sets this view apart from the background veil, this is typically a solid 9 patch image.
  3. Finally, your views can be added to the linear layout as a last step. Since these views will be enclosed inside the LinearLayout, they will appear on a solid background and not the veil.

Here is the code to do this:

  // create the enclosing view, etc.
  LinearLayout enclosingPanel = new LinearLayout(ctx);
  {
    enclosingPanel.setOrientation(LinearLayout.VERTICAL);
    enclosingPanel.setGravity(Gravity.CENTER);
    LayoutUtils.Layout.WidthFill_HeightFill.applyLinearLayoutParams(enclosingPanel);
    enclosingPanel.setBackgroundResource(<dialog_bg>);
  }

  // create the stuff that goes inside the enclosing view
  {
    LinearLayout enclosedPanel = new LinearLayout(ctx);
    LayoutUtils.Layout.WidthFill_HeightWrap.applyLinearLayoutParams(enclosedPanel);
    enclosedPanel.setOrientation(LinearLayout.HORIZONTAL);
    enclosedPanel.setBackgroundResource(<linearlayout_bg>);

    enclosedPanel.addView(content);

    enclosingPanel.addView(enclosedPanel);

  }

  // actually create the dialog
  Dialog dialog = new Dialog(ctx, android.R.style.Theme_Translucent_NoTitleBar);
  dialog.setContentView(enclosingPanel);
  return dialog;

You can place whatever view you want inside the enclosedPanel and then show() the dialog.