Software Development

Pro tip: Convert Android pixels to inches

A common question amongst Android developers about supporting multiple screens is: How do I convert pixels to inches? Here's a simple way to accomplish that task.

android091913.png

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.

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="left|center"
    android:gravity="center" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="#00ff00"
        android:textColor="#000000"
        android:text='2"'/>
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Scale TextView"
        android:id="@+id/scale_button" />

</LinearLayout>

3. Let's move on to the /src/MainActivity.java 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.

MainActivity.java
package com.authorwjf.twoinches;

import android.app.Activity;
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;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViewById(R.id.scale_button).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		View textView = findViewById(R.id.text);
		setViewWidthInInches(TWO_INCHES, textView);
	}
	
	private void setViewWidthInInches(float inches, View v) {
		DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        float mXDpi = metrics.xdpi;
	    int twoInches = Math.round(inches*mXDpi);
        v.setLayoutParams(new LinearLayout.LayoutParams(twoInches, LayoutParams.WRAP_CONTENT));
        v.requestLayout();
	}

}

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

Figure A

measuredonandroiddevice081914.png

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.

About

William J Francis began programming computers at age eleven. Specializing in embedded and mobile platforms, he has more than 20 years of professional software engineering under his belt, including a four year stint in the US Army's Military Intellige...

1 comments
stevec
stevec

Not to quibble unnecessarily, but since you're trying to get an accurate conversion to inches, it seems to me that that green line is about 1-15/16", not "exactly 2 inches."

Editor's Picks