动画图像并使其在最后停止?

时间:2012-02-09 10:35:57

标签: android animation slide

我正在尝试制作一个动画,点击右键可以将图像从布局右侧滑动,然后点击左键将图像从布局左侧滑动到图像的左侧。

到目前为止我已经这样做了:

public class DenemeActivity extends Activity implements View.OnClickListener {

Button LeftSlide, RightSlide;
View image;
int width;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LeftSlide = (Button) findViewById(R.id.slideLeft);
    RightSlide = (Button) findViewById(R.id.slideRight);
    image = (View) findViewById(R.id.imageV);
    width = getWindowManager().getDefaultDisplay().getWidth(); ;
    LeftSlide.setOnClickListener(this);
    RightSlide.setOnClickListener(this);      

}

public void onClick(View v) {
    runOnAnimation(v.getId(), image);
}

void runOnAnimation(final int id, final View view) {

    AnimationSet animation = new AnimationSet(true);
    TranslateAnimation translateAnimation = null;

    int fromXDelta = view.getLeft();

    if(id == LeftSlide.getId())
        translateAnimation = new TranslateAnimation(fromXDelta, 0, 0, 0);
    else if(id == RightSlide.getId())
        translateAnimation = new TranslateAnimation(fromXDelta, width - view.getWidth() - fromXDelta , 0, 0);

    translateAnimation.setDuration(1000);
    animation.addAnimation(translateAnimation);
    animation.setAnimationListener(new AnimationListener() {

        public void onAnimationEnd(Animation v) {
            v.reset();
            view.clearAnimation();

            // Change view to state B by modifying its layout params and scroll
            if(id == LeftSlide.getId())
                view.layout(0, 0, view.getWidth(), view.getHeight());
            else if(id == RightSlide.getId())
                view.layout(width - view.getWidth(), 0, width, view.getHeight());               
        }

        public void onAnimationRepeat(Animation v) {}
        public void onAnimationStart(Animation v) {}
    });
    view.startAnimation(animation);
}    
}

我查了点:

宽度= 480

fromXDelta = 408(点击左侧时)

所以它确实没有超出边界,但当我点击左键时,图像来自边界?它能为此带来什么? 提前谢谢......

1 个答案:

答案 0 :(得分:1)

我认为您想要移动的视图的位置类型错误。 尝试获取View的位置并按如下方式实现翻译:

int fromPos = view.getLeft();
int toPos   = 0;
if(id == LeftSlide.getId()) {
  translateAnimation = new TranslateAnimation(fromPos, toPos, 0, 0);
} else {
  toPos = getWidth()-view.getWidth();
  translateAnimation = new TranslateAnimation(fromPos, toPos, 0, 0);
}

这应该可以解决问题。