2012-03-14 61 views
16

在我的应用程序中有一个LinearLayout,它具有0布局高度。当我点击按钮时,这个布局高度应该是LayoutParams.WRAP_CONTENT。这是我在onclicklistner中使用的代码。更改LinearLayout中LayoutParams的动画

LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
slider.setLayoutParams(lp); 

我想动画这个。我如何设置动画到滑块。

+1

你想要滑块上的动画吗? – 2012-03-14 04:40:20

+0

@Nixit Patel yes – Chrishan 2012-03-14 04:52:59

+0

@NixitPatel:你想实现滑块动画? – 2012-03-14 05:00:02

回答

25

我觉得你只是想从0高度动画着眼于它的最终高度,你可以用自定义动画做到这一点:

public class ShowAnim extends Animation { 
    int targetHeight; 
    View view; 

    public ShowAnim(View view, int targetHeight) { 
     this.view = view; 
     this.targetHeight = targetHeight; 
    } 

    @Override 
    protected void applyTransformation(float interpolatedTime, Transformation t) { 
     view.getLayoutParams().height = (int) (targetHeight * interpolatedTime); 
     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; 
    } 
} 

并在代码中这样做是为了启动动画:

Animation ani = new ShowAnim(headerView, 100/* target layout height */); 
ani.setDuration(2000/* animation time */); 
headerView.startAnimation(ani); 
+1

如何在没有它的情况下每次都从零开始做这件事?如果我这样做了一次,目标布局高度为100,然后再以200的目标布局时间,我希望它从0 - > 100,然后100 - > 200. – Andrew 2013-11-01 19:30:50

+0

如果您想要从100 - > 200,那么只需修改这一行'view.getLayoutParams()。height =(int)(targetHeight * interpolatedTime);'就像'view.getLayoutParams()。height = initialHeight/* 100在你的情况*/+ int)(targetHeight/* 200 in your case */- initialHeight * interpolatedTime);' – Kai 2013-11-02 01:09:39

+1

当initialHeight为0时,什么都不起作用。根本没有视觉上的改变。 – Andrew 2013-11-04 16:06:36

1

由于我们在android中自从JELLYBEAN开始布局转换,我们可以使用它来代替使用动画对象。

下面的文章详细解释它。 https://proandroiddev.com/the-little-secret-of-android-animatelayoutchanges-e4caab2fddec

总之,我们只需要这个代码 -

tView.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING); 
tView.setLayoutParams(lp); 

这里LP将是布局PARAMS

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams 
          (RelativeLayout.LayoutParams.MATCH_PARENT, newHeight); 

还有一点要补充将在布局中加入这一行文件,到将要进行转换的布局。

android:animateLayoutChanges="true"