ImageView setMargins not working

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

I'm trying to move a 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 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(lp);

Small image does not move. I want to be able to move a small image around the layout.

LATER CHANGE: After trying a few tips, I came to the conclusion that it is easier to just make your own view and override onDraw to complete the task.

+3
source share
3 answers

Everything in FrameLayout is fixed in the upper left corner and cannot be moved even by setting fields. But you can get the same result using a pad ...

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

, :

lp.gravity = Gravity.LEFT | Gravity.TOP;
+11
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 managed to use setMargin in the same way as usual setPadding.. however you need to set a new layout parameter for each imageviewone that you like to set margin

+3
source

Source: https://habr.com/ru/post/1768038/


All Articles