Your Name

Your Email

Subject

Your Message

Converting dp to px and opposite in Android

It was amazing how many wrong answers are there in stackoverflow (wchich people state correct). Some of them have like 100 upvotes.

I’ve decided to post the correct way of doing that.

P.S.
This and much more is a part of AprilApps Android library, which is open source on bitbucket.org.

public int pixelsToDp(int px) {
		int dp = (int) (px / getResources().getDisplayMetrics().density);
	    return dp;
	}
	
	public int dpToPixels(int dp) {
	    int px = (int) (dp * getResources().getDisplayMetrics().density);
	    return px;
	}

Tags: , , ,