Avisek Chakraborty
Avisek Chakraborty

Reputation: 8309

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

Upvotes: 20

Views: 48162

Answers (6)

Roman Black
Roman Black

Reputation: 3497

You can try this

FrameLayout.LayoutParams srcLp = (FrameLayout.LayoutParams)searchPin.getLayoutParams();
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(srcLp.width, srcLp.height, srcLp.gravity);

lp.setMargins(srcLp.leftMargin, srcLp.topMargin, srcLp.rightMargin, srcLp.bottomMargin);

searchPin.setLayoutParams(lp);

Upvotes: 3

hovanessyan
hovanessyan

Reputation: 31433

I think what you're missing is that, when you set programmatically the parameters for an element, those parameters are provided actually to the parent View, so that it knows how to position the element. The parameters are not set back to the element itself. Consider the following code example. Also note, that the layout parameters are of the type of the parent.

LinearLayout linearLayout = new LinearLayout(this);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.FILL_PARENT, 
     LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(6,6,6,6);

Button someButton=new Button(this);
someButton.setText("some text");

linearLayout.addView(someButton, layoutParams);

Upvotes: 5

sherpya
sherpya

Reputation: 4936

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

Upvotes: 13

jdo59
jdo59

Reputation: 194

Try this:

params.gravity = Gravity.TOP;

Upvotes: 17

stef
stef

Reputation: 525

Just use LayoutParams instead of FrameLayout.LayoutParams

LayoutParams params = (LayoutParams) searchPin.getLayoutParams();
params.setMargins(135, 176, 0, 0);
searchPin.setLayoutParams(params);

this worked for me

Upvotes: -1

Avisek Chakraborty
Avisek Chakraborty

Reputation: 8309

simple solution-

searchPin = (ImageView) findViewById(R.id.waypts_search_pin);
searchPin.setPadding(135, 176, 0, 0);

Upvotes: 2

Related Questions