soren.qvist
soren.qvist

Reputation: 7416

Setting the height of a view in dp units by code?

I was wondering if it's possibly to change the height of a LinearLayout in my java code from something like 100dp to 200dp ?

Upvotes: 1

Views: 2363

Answers (3)

philipp
philipp

Reputation: 4183

// The gesture threshold expressed in dp
private static final float GESTURE_THRESHOLD_DP = 16.0f;

// Get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
mGestureThreshold = (int) (GESTURE_THRESHOLD_DP * scale + 0.5f);

// Use mGestureThreshold as a distance in pixels...

The DisplayMetrics.density field specifies the scale factor you must use to convert dp units to pixels, according to the current screen density. On a medium-density screen, DisplayMetrics.density equals 1.0; on a high-density screen it equals 1.5; on an extra high-density screen, it equals 2.0; and on a low-density screen, it equals 0.75. This figure is the factor by which you should multiply the dp units on order to get the actual pixel count for the current screen. (Then add 0.5f to round the figure up to the nearest whole number, when converting to an integer.) For more information, refer to the DisplayMetrics class.

Answer from android documentation so you don't have to search for content

Upvotes: 0

DArkO
DArkO

Reputation: 16110

Yes.

(int) TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP, 2, this.getResources()
        .getDisplayMetrics()));

also you can add a dimension in values and get it from resources.

Dimension values

Upvotes: 5

ihrupin
ihrupin

Reputation: 6972

Try this tutorial http://developer.android.com/guide/practices/screens_support.html#DensityConsiderations

It can help you convert dp to px. This px value you can set in LayoutParams. Hope it's useful

Upvotes: 1

Related Questions