Search code examples
androidandroid-imageview

Moving an ImageView


I have a problem when I tap on the "Cucina" button the white circle (top left of the photo) should move on the left of the button itself. I'm using the following code:

 filter2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(30, 30);
            layoutParams.setMargins(Math.round(filter2.getX()), Math.round(filter2.getY()), 0, 0);
            cerchioMenu.setLayoutParams(layoutParams);

        }
    });

but it does not work, any suggestions?

enter image description here


Solution

  • Inside onClick event, you should get the button's coordinate like this:

    int[] location = new int[2];
    button.getLocationInWindow(location);
    

    The location array will hold the button x and y coordinates. Now animate the white circle like this:

    mCircle.animate().y(location[1]).setDurarion(200).start();
    

    Remember to check for null and array index of location before doing any call on the array.