Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get margin of a View

How can I get the margin value of a View from an Activity? The View can be of any type.

After a bit of searching I found out ways to get padding of a view, but couldn't find anything on Margin. Can anyone help?

I tried something like this,

ViewGroup.LayoutParams vlp = view.getLayoutParams(); int marginBottom = ((LinearLayout.LayoutParams) vlp).bottomMargin; 

This works, but in the above code I have assumed the view to be a LinearLayout. But I need to get the margin attribute even when I don't know the view type.

like image 447
Arnab Chakraborty Avatar asked Sep 19 '11 07:09

Arnab Chakraborty


People also ask

What is a layout margin?

android:layout_margin. Specifies extra space on the left, top, right and bottom sides of this view.

How do you set margin top programmatically?

You should use LayoutParams to set your button margins: LayoutParams params = new LayoutParams( LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT ); params.

How do I set margins to recyclerView programmatically?

margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView.


2 Answers

try this:

View view = findViewById(...) //or however you need it LayoutParams lp = (LayoutParams) view.getLayoutParams(); 

margins are accessible via

lp.leftMargin; lp.rightMargin; lp.topMargin; lp.bottomMargin; 

edit: perhaps ViewGroup.MarginLayoutParams will work for you. It's a base class for other LayoutParams.

ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams(); 

http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html

like image 119
Vladimir Avatar answered Oct 10 '22 05:10

Vladimir


Try

ViewGroup.MarginLayoutParams vlp = (MarginLayoutParams) view.getLayoutParams()  vlp.rightMargin vlp.bottomMargin vlp.leftMargin vlp.topMargin 

This returned the correct margains for my view atleast.

http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html

like image 45
Freddroid Avatar answered Oct 10 '22 04:10

Freddroid