简体   繁体   English

Android:以编程方式在FrameLayout中设置边距-不起作用

[英]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- 从xml到任何地方,

android:layout_marginLeft="135dp"

what can be the reason? 可能是什么原因? am i missing something! 我错过了什么!

-thnx -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 我有一个RelativeLayout的FrameLayout子元素,因此框架试图将FrameLayout参数转换为RelativeLayout,我这样解决了

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而不是FrameLayout.LayoutParams

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

this worked for me 这对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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