Trying to move an ImageView into a touch event through setLayoutParams, the image view does not move

I have a small ImageView inside a full-screen FrameLayout, and I would like to set it so that when I touch FrameLayout, the image will be viewed at this position.

I read all the other questions I can find about moving an ImageView, but I did not see why my solution is still not working.

In a custom view that extends FrameLayout:

@Override public boolean onInterceptTouchEvent(MotionEvent event){ if(event.getActionMasked() == MotionEvent.ACTION_DOWN){ ImageView iv = (ImageView) this.findViewById(R.id.draggedImage); FrameLayout.LayoutParams params = (LayoutParams) iv.getLayoutParams(); params.leftMargin = (int) event.getX(); params.bottomMargin = (int) event.getY(); iv.setLayoutParams(params); iv.invalidate(); invalidate(); } return true; } 

I changed the marker layoutparams to reflect the new position of the touch, and invalidated the image and framemayut (not sure which one I should do), but the imageView does not move (it just sits always in the upper left corner of the frame corner).

I also checked that this method is called when I touch the screen, and the parameters change using normal values โ€‹โ€‹of X and Y.

My layout:

 <CustomFrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- some other unrelated views --> <ImageView android:id="@+id/draggedImage" android:layout_width="100dp" android:layout_height="100dp" android:src="@drawable/pause" /> </CustomFrameLayout> 

Edit: I have to mention that I am trying to customize the API level 10, so I can not use any support for cellular advertising orientation :(

+4
source share
4 answers

As a result of trial and error and search, it turned out that I was missing this call:

params.gravity = Gravity.LEFT | Gravity.BOTTOM;

Initially, gravity was -1, so the fields had no effect, because they did not know which side he had to base the fields on. Adding gravity gives her a side to snap so that she can be moved an amount in the field.

Now it works fine.

+3
source

I believe that you want to install the top and left padding. See the next question that explains this better than I could. The difference between stock and brand View

+1
source

I think that:

 iv.setLayoutParams(params); 

Just set params parameter to layout iv, which is FrameLayout .

Perhaps you can set the position of ImageView to iv.setX() ; iv.setY() ;

+1
source

I found Tim's solution:

params.gravity = Gravity.LEFT | Gravity.BOTTOM;

To change the field of view, it became necessary only when working on devices with android level 10 or less!

The problem did not appear at levels 14 or 17.

Adding the above code gave the desired behavior at all levels of the android ... Thanks Tim.

0
source

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


All Articles