Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Set margins in a FrameLayout programmatically- not working

here is the code-

FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) searchPin.getLayoutParams();
params.setMargins(135, 176, 0, 0);
//params.leftMargin = 135; // also not worked 
//params.topMargin = 376;
searchPin.setLayoutParams(params);

Where ever, from xml its working-

android:layout_marginLeft="135dp"

what can be the reason? am i missing something!

-thnx

like image 431
Avisek Chakraborty Avatar asked Nov 12 '11 00:11

Avisek Chakraborty


People also ask

How do I set margins programmatically in Android?

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?

How do I set margins to recyclerView programmatically? margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams.

How do you set margins in Java?

We can set a margin to a JButton by using the setMargin() method of JButton class and pass Insets(int top, int left, int bottom, int right) as an argument.


2 Answers

Try this:

params.gravity = Gravity.TOP;
like image 159
jdo59 Avatar answered Nov 02 '22 19:11

jdo59


I had a FrameLayout child of a RelativeLayout so the framework was trying to cast FrameLayout params to RelativeLayout, I solved this way

FrameLayout mylayout = (FrameLayout) view.findViewById(R.id.mylayout);
ViewGroup.MarginLayoutParams params = (MarginLayoutParams) mylayout.getLayoutParams();
params.setMargins(1, 2, 3, 4);
mylayout.setLayoutParams(params);
like image 26
sherpya Avatar answered Nov 02 '22 18:11

sherpya