Android: Set margins in a FrameLayout programmatic

2019-01-24 05:32发布

问题:

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

回答1:

Try this:

params.gravity = Gravity.TOP;


回答2:

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


回答3:

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


回答4:

simple solution-

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


回答5:

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


回答6:

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