Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinearLayout.LayoutParams how to use dip...?

Tags:

android

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);

like image 354
LuxuryMode Avatar asked May 18 '11 22:05

LuxuryMode


2 Answers

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);
like image 89
Gligor Avatar answered Nov 15 '22 22:11

Gligor


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 ^^

like image 34
Houcine Avatar answered Nov 15 '22 21:11

Houcine