Friday 9 September 2011

GWT: creating a dialog prompt or popup panel

The class to use is DialogBox or PopupPanel and both are pretty straightforward to use. You just create an instance of DialogBox (or PopupPanel), make calls to the set methods you need (setTitle(,,,), setText(...), setAnimationEnabled(...), setGlassEnabled(...), addStyleName(...), setWidget(...) etc) and then call the DialogBox's show() or center() method to show it and the DialogBox's hide() method to hide it.

The only differences I see right now (I'm sure there are others) is that a DialogBox can be dragged around by the user and a PopupPanel on the other hand has an auto-hide property which could be handy.

Thursday 1 September 2011

Android: methods for converting pixels to density-independent pixels, and vice versa

When creating Views or setting heights, widths, margins and so forth of Views programmatically (i.e. not in the xml layout files), the values to set are all in pixels, which is no good when you're trying to work with density-independent pixels (dips). So here's a couple of methods convert from pixels to dips and vice versa should the need arise:

/**
 * Converts the given number of pixels
 * to the corresponding number of density-independent pixels
 * using the formula: dip = px / (dpi / 160).
 */
public static float convertPxToDip(Context context, float pixels) {
 DisplayMetrics dm = context.getResources().getDisplayMetrics();
 return pixels / dm.density; // dm.density gives the scaling factor

 // alternative way of doing it
 // return (pixels * DisplayMetrics.DENSITY_DEFAULT) / (dm.densityDpi);
}

/**
 * Converts the given number of density-independent pixels
 * to the corresponding number of pixels
 * using the formula: px = dip * (dpi / 160).
 */
public static float convertDipToPx(Context context, float dip) {
 DisplayMetrics dm = context.getResources().getDisplayMetrics();
 return dip * dm.density; // dm.density gives the scaling factor

 // alternative way of doing it
 // return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, dm);
}