2010-10-05 81 views
3

我有一个FrameLayout,它有2个图像,一个填充FrameLayout的大图像和一个我想要移动的很小的图像。ImageView setMargins不起作用

我尝试移动小一个这样的: xml文件

<FrameLayout android:id="@+id/layTrackMap" 
         android:layout_width="wrap_content" 
           android:layout_height="wrap_content" 
           android:visibility="gone"> 

     <ImageView android:id="@+id/imgTrackMap" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       /> 

     <ImageView android:id="@+id/imgPosition" 
       android:layout_width="wrap_content" 
       android:src="@drawable/position" 
       android:layout_height="wrap_content" 

       /> 

     </FrameLayout> 

,代码:

imgPosition = (ImageView)findViewById(R.id.imgPosition); 

    FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); 

    //Neither this: 
    //lp.setMargins(30, 20, 0, 0); 

    //Or this 
    lp.leftMargin=30; 
    lp.topMargin=80; 

    imgPosition.setLayoutParams(lp); 

小画面不动。我希望能够在布局中移动小图像。

后编辑: 在尝试了几个建议后,我得出结论,更简单的做一个自定义视图并重写onDraw来完成这项工作。

回答

2

FrameLayout中的所有内容都固定在左上角,即使通过设置页边距也无法移动。但是你可以通过使用填充得到同样的结果...

imgPosition.setPadding(30, 80, 0, 0); 
+0

这在理论上是有效的。但是,如果您想添加背景可绘制(例如,指示您的图像被选中),这将拉伸它。更好的解决方案是使用边距定义LayoutParam对象,并将Fede的重力设置为Fede。或者,如果您想要走这条路线,请进行自定义视图。 – Dan 2011-05-29 12:24:45

11

您还应该设置重力为了使用边距:

lp.gravity = Gravity.LEFT | Gravity.TOP; 
+0

谢谢,它适用于我 – ihrupin 2011-08-17 14:49:06

+0

出于某种原因,只有像这样的代码中设置重力解决了我的问题;奇怪的是,在XML布局中设置重力并没有。 – Trevor 2012-01-29 14:00:56

+0

谢谢!有用! – Michael 2016-02-15 11:28:39

3
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.WRAP_CONTENT, 
        FrameLayout.LayoutParams.WRAP_CONTENT); 
lp.gravity = Gravity.LEFT | Gravity.TOP; 
lp.setMargins(left, top, right, bottom); 
imgPosition1.setLayoutParams(lp); 

lp = new FrameLayout.LayoutParams(
       FrameLayout.LayoutParams.WRAP_CONTENT, 
       FrameLayout.LayoutParams.WRAP_CONTENT); 
lp.gravity = Gravity.LEFT | Gravity.TOP;  
lp.setMargins(left, top, right, bottom); 
imgPosition2.setLayoutParams(lp); 

我还是设法使用setMargin就像一个常规的setPadding ..不过你必须设置一个新的布局参数为每个imageview你想设置一个保证金