One cool thing about the Android OS for users and device manufacturers is that there aren’t restrictions on display sizes. At one end of the spectrum are Android devices with tiny displays like the wearable G Watch; at the other end live devices with enormous displays, like Samsung’s Galaxy Mega. As developers, we must write code that can play nice at both extremes and anywhere in between.

To aid developers in the lofty goal of writing user interface code that can adapt to a myriad of display sizes, Google has armed us with tools to discover screen size, density, orientation, resolution, and everyone’s favorite unit of measurement: dp (density-independent pixels). Google has a very good (and very long) detailed guide to supporting multiple screens.

However, even with the official guidance from Google, a common question I see pop up in the forums is: “How do I convert pixels to inches?” The sample that follows demonstrates an easy way to achieve just that. You can follow along with the step-by-step tutorial, or download and import the entire project directly into Eclipse.

1. Create a new Android project in Eclipse. Target SDK 14 (ICS) or better.

2. Modify the /res/layout/activity_main.xml file to contain a text view and a button both wrapped in a linear layout.


3. Let’s move on to the /src/ file. The onCreate() and the onClick() overrides should be familiar to you already — it is the setViewWidthInInches() where we are performing the sizing of our view. The general idea is to get the pixels per inch and then multiply this number by our desired width in inches.
package com.authorwjf.twoinches;

import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity implements OnClickListener {

private static final float TWO_INCHES = 2f;

protected void onCreate(Bundle savedInstanceState) {

public void onClick(View v) {
View textView = findViewById(;
setViewWidthInInches(TWO_INCHES, textView);

private void setViewWidthInInches(float inches, View v) {
DisplayMetrics metrics = new DisplayMetrics();
float mXDpi = metrics.xdpi;
int twoInches = Math.round(inches*mXDpi);
v.setLayoutParams(new LinearLayout.LayoutParams(twoInches, LayoutParams.WRAP_CONTENT));


Figure A shows an actual Nexus 7 with a ruler laid along the view in question — exactly 2 inches.

Figure A

Note: A number of developers have reported issues with the Android software emulators returning an incorrect screen density; I have run into this a couple of times. Since the algorithm we are using to layout our view width depends on knowing the device’s display density, I recommend running the above code sample on actual hardware only.