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