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

时间:2011-11-12 00:32:57

标签: android android-layout android-framelayout

这是代码 -

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

无论如何,从xml开始工作 -

android:layout_marginLeft="135dp"

可能是什么原因?我错过了什么!

-thnx

6 个答案:

答案 0 :(得分:16)

试试这个:

params.gravity = Gravity.TOP;

答案 1 :(得分:8)

我有一个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);

答案 2 :(得分:3)

我认为您缺少的是,当您以编程方式设置元素的参数时,这些参数实际提供给父视图,以便它知道如何定位元素。参数不会设置回元素本身。请考虑以下代码示例。另请注意,布局参数属于父类型。

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

答案 3 :(得分:2)

简单的解决方案 -

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

答案 4 :(得分:2)

你可以试试这个

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

答案 5 :(得分:-1)

只需使用LayoutParams而不是FrameLayout.LayoutParams

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

这对我有用