Android: Set margins in a FrameLayout programmatic

2019-01-24 05:49发布

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

6条回答
在下西门庆
2楼-- · 2019-01-24 06:05

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楼-- · 2019-01-24 06:17

simple solution-

searchPin = (ImageView) findViewById(R.id.waypts_search_pin);
searchPin.setPadding(135, 176, 0, 0);
查看更多
甜甜的少女心
4楼-- · 2019-01-24 06:18

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);
查看更多
Melony?
5楼-- · 2019-01-24 06:21

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楼-- · 2019-01-24 06:26

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

查看更多
▲ chillily
7楼-- · 2019-01-24 06:30

Try this:

params.gravity = Gravity.TOP;
查看更多
登录 后发表回答