ImageView setMargins不起作用

时间:2010-10-05 10:07:31

标签: android imageview

我有一个FrameLayout,它有2个图像,一个填充FrameLayout的大图像和一个我想要移动的非常小的图像。

我尝试像这样移动小的: 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);

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

稍后编辑: 在尝试了几个建议之后,我得出的结论是,只需创建一个自定义View并覆盖onDraw就可以完成这项工作。

3 个答案:

答案 0 :(得分:11)

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

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

答案 1 :(得分: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); 

我确实设法像常规setPadding一样使用setMargin ..但是你必须为每个imageview设置一个新的布局参数来设置边距

答案 2 :(得分:2)

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

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