Android Tips, Techniques and Theory

PART 2: Creating Content with Java with Android Studio (Programming required)

With Simple Recipes

Go Back To TOC

Units of Measurement

While you can easily set units of measurement in an XML file, you can also use Java to set units of measurement.

sp and dp (Android Specific)

Every view or widget has a layoutParams object that has the layout parameters (e.g., height, width)

EXAMPLE: Set Object Height

Button showDialog = (Button)findViewById(R.id.showDialogID);

showDialog.getLayoutParams().height = 100;

This will set the height of the showDialog button to 100 pixels. It is best to use dp unit of measurement instead. To do this

  1. Convert physical pixels to device-independent pixels using the TypedValue.applyDimension and then get screen density and resolution from the getResources().getDisplayMetric().

    float pixels = TypedValue.applyDimension(TypeValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrices());
    showDialog.getLayoutParams().height = (int) pixels;

  2. Run the app to see that the size has been changed.