ImageView更改宽度动画

时间:2016-08-20 13:02:09

标签: android animation imageview

我正在尝试在ImageView上制作动画来改变它的宽度,但没有发生任何事情

这是我的代码

final ImageView NewsDeitalHeaderImage = (ImageView) findViewById(R.id.NewsDeitalHeaderImage);
     NewsDeitalHeaderImage.setImageResource(NewsDeitalSharedImage);

     ValueAnimator anim = ValueAnimator.ofInt(  NewsDeitalHeaderImage.getMeasuredWidth() , WindowManager.LayoutParams.MATCH_PARENT);
         anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
         @Override
         public void onAnimationUpdate(ValueAnimator valueAnimator) {
             int val = (Integer) valueAnimator.getAnimatedValue();
             LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)NewsDeitalHeaderImage.getLayoutParams();
             layoutParams.width =val;
             NewsDeitalHeaderImage.setLayoutParams(layoutParams);
         }
     });
     anim.setDuration(300);
     anim.start(); 

1 个答案:

答案 0 :(得分:0)

问题是您使用错误的值来获得最终宽度。默认情况下,LayoutParams.MATCH_PARENT会返回 -1 ,这就是您没有正确动画的原因。所以我想你需要使用getParent().getMeasuredWidth() NewsDeitalHeaderImage方法来获得正确的最终宽度值:

...
ValueAnimator anim = ValueAnimator.ofInt(NewsDeitalHeaderImage.getMeasuredWidth(), NewsDeitalHeaderImage.getParent().getMeasuredWidth());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator valueAnimator) {
        // your code here for animation
    }
});
...