17

I'm trying to set the height of my LinearLayout to 45 dip.

How can I do this when extending LinearLayout?

Right now I just did: LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 45);

LuxuryMode
  • 33,401
  • 34
  • 117
  • 188

3 Answers3

48

The best way to go for this kind of issue is create a dimens.xml file under values and put in your dip values there, and then in code you pull the dimensions from that file. That's what resources are for, right? =)

Here's an example of a dimens.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="about_image_bottom">0dp</dimen>
</resources>

And this is how you can pull it out in code:

RelativeLayout.LayoutParams iv_params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
iv_params.setMargins(0, 0, 0, (int) getResources().getDimension(R.dimen.about_image_bottom));

And then you set the parameters to whatever object you need, in my case to the ImageView iv:

iv.setLayoutParams(iv_params);
Gligor
  • 2,862
  • 2
  • 33
  • 40
  • Shouldn't dimens.xml contains dimen in dip instead of dp? As dip is much more precise... – Salmaan Dec 22 '14 at 13:02
  • dip == dp, if you check the answer here, they have all the information about what the different units of measurement mean in Android http://stackoverflow.com/questions/2025282/difference-between-px-dp-dip-and-sp-in-android – Gligor Dec 22 '14 at 20:44
  • 1
    Great flawless solution :) – Skynet Nov 19 '15 at 06:01
16

You can use DisplayMatrics and determine the screen density. Something like this:

int pixelsValue = 5; // margin in pixels
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(pixelsValue * d);

Hope it helps ^^

Houcine
  • 24,001
  • 13
  • 56
  • 83
-1

Probably the best way would be to specify it in XML. Replace the normal LinearLayout tag with what ever class you created to extend the LinearLayout in the XML tag:

<com.example.MyLinearLayout 
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="45dp" 
              android:orientation="vertical" >
 ....

See here for more info.

dbryson
  • 6,047
  • 2
  • 20
  • 20