简体   繁体   中英

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

尝试这个:

params.gravity = Gravity.TOP;

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

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

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

simple solution-

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM