简体   繁体   中英

Android - Send imageView to X Y position

i have an imageView A that starts at right screen. I want to set X and Y position programatically. To move the imageView near the top left corner, i have to set a X = -1497 Y = 20. What i dont understand is why X = -1497. I think because it tooks the (0,0) position where the imageView starts, but how to catch the (0,0) at top left screen?

This is because, for all screen i have to calculate a % to move the imageView to same place always, but how to do it with negative values.

Point origImagePos = new Point(-1460, 20);

public void moveImageView(View view){
  ObjectAnimator objectX;
  ObjectAnimator objectY;
  AnimatorSet animatorXY;

  objectX = ObjectAnimator.offFloat(view, "translationX", origImagePos.x);
  objectY = ObjectAnimator.offFloat(view, "translationY", origImagePos.y);
  animatorXY.playTogether(objectX, objectY);
  animatorXY.setDuration(500);
  animatorXY.start();
}

Greets

translationX works relative to view. Try this,

objectX = ObjectAnimator.offFloat(view, "X", 20);
objectY = ObjectAnimator.offFloat(view, "Y", 20);

Actually you could cut most your code using ViewPropertyAnimator instead of ObjectAnimator.

public void moveImageView(View view){

    view.animate().translationX(0).translationY(0).setDuration(500);

}

thats all the code you need and should move your View to the top left corner.

You could always enhance your method for later animations like this for example :

// You should also always use Interpolators for more realistic motion.

public void moveImageView(View view, float toX, float toY, int duration){

     view.animate()
        .setInterpolator(new AccelerateDecelerateInterpolator())
        .translationX(toX)
        .translationY(toY)
        .setDuration(duration);
}

and then call it like :

moveImageView(yourImageView, 0, 0, 500);

To get the coordinates of the device dynamically so you know where to move :

float screenWidth = getResources().getDisplayMetrics().widthPixels;
float screenHeight = getResources().getDisplayMetrics().heightPixels;

screenWidth + screenHeight would be the coordinates of the right bottom corner.

Top Left corner coordinates are simply 0, 0.

Center of screen coordiantes are logically (screenWidth / 2) + (screenHeight / 2).

Hope that makes your life easier in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM