Animations: How should I translate an ImageView ou

2019-07-17 04:31发布

I am using a translate animation:

<?xml version="1.0" encoding="utf-8"?>
<set
  xmlns:android="http://schemas.android.com/apk/res/android">
  <translate
    android:fromXDelta="-75%p"
    android:toXDelta="0%p"
    android:duration="1000" />
</set>

on a basic ImageView. This animation will slide the image out from the left until it reaches the right edge of the screen. I have an OnClickListener set on the ImageView which toggles it from sliding out and in - works great.

Problem: It seems that the ImageView is not actually moving it's coordinates, but it just looks like it's moving. When the ImageView is only partly visible(waiting to be animated out into the screen), if I click on an area where the ImageView would be if it were slid out, the animation starts(OnClickListener is fired off).

I wasn't clicking on the ImageView!

Question: So, components with an animation such as this do not actually move? How can I handle this onClick event, as it would be unexpected for an animation to occur when pressing on the screen where the ImageView is not visible to the user?

2条回答
Animai°情兽
2楼-- · 2019-07-17 05:02

You're right, the components don't really move, only their rendered bitmap buffer. After animating out of the screen, you can use View.setVisibility(View.GONE); to make it really disappear.

If your target is to have a small part of the view still visible to allow the user to slide it back on the screen, you might consider using a SlidingDrawer.

查看更多
\"骚年 ilove
3楼-- · 2019-07-17 05:16

You can actually create your own animation that actually moves the ImageView, that way you'll always be able to click it.

Of course it will depend on your circumstance, but say you wanted to move the image view on the X axis by adjusting the left margin, you would have something like:

public class ViewLeftMarginAnimation extends Animation {
    int startMargin;
    int targetMargin;
    View view;

    public ViewGrowAnimation(View view, int start, int target) {
        this.view = view;
        this.start = height;
        this.targetHeight = toHeight;
        this.setInterpolator(new DecelerateInterpolator());
        this.setDuration(1000);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        int newMargin = (int) (startMargin + ((targetMargin - startMargin) * interpolatedTime));
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        p.leftMargin = newMargin;
        view.setLayoutParams(p);
        view.requestLayout();
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}
查看更多
登录 后发表回答