开发者

ImageView setMargins doesn't work

I have a FrameLayout that has 2 images, a big one that that fills the FrameLayout and a very small one that I want to move around.

I try to move the small one like this: xml file

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

and the code:

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开发者_StackOverflow(lp);

The small image doesn't move. I want to be able to move the small image around in layout.

LATER EDIT: After trying several suggestions I came to the conclusion that is simpler to just make a custom View and override onDraw to do the job.


You should also set the gravity in order to use margins:

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


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

i did manage to use setMargin just like a regular setPadding..however you have to set a new layout parameter for every imageview you like to set a margin


Everything in a FrameLayout is fixed to the top left and can't be moved, even by setting margins. But you can get the same result by using padding...

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜