动画和setVisibility

时间:2011-06-30 15:24:57

标签: android animation

我有一个LinearLayout,我希望能够通过点击“更多详细信息”链接来显示/隐藏。我通过调用

来做到这一点
moreDetailsSection.setVisibility(View.VISIBLE);

moreDetailsSection.setVisibility(View.GONE);

显示/隐藏它。这工作正常,但我想添加一个动画,使布局字段很好地滑动,但这只是在第一次使字段可见时运行,如果我隐藏它并再次显示该字段只是突然出现。这是动画代码(moreDetailsS​​ection是有问题的布局):

      AnimationSet set = new AnimationSet(true);

      Animation animation = new AlphaAnimation(0.0f, 1.0f);
      animation.setDuration(250);
      set.addAnimation(animation);

      animation = new TranslateAnimation(
          Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f,
          Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f
      );
      animation.setDuration(150);
      set.addAnimation(animation);

      LayoutAnimationController controller =
          new LayoutAnimationController(set, 0.25f);
      moreDetailsSection.setLayoutAnimation(controller);

关于如何进行此运行的任何建议每次显示布局而不仅是第一次?

3 个答案:

答案 0 :(得分:14)

我认为moreDetailsS​​ection最初是不可见的。 您只需创建Animation对象,并在单击更多详细信息链接时调用以下代码。

moreDetailsSection.startAnimation(animation);
moreDetailsSection.setVisibility(View.VISIBLE);

答案 1 :(得分:2)

您可以在视图中使用此行进行该布局:

android:animateLayoutChanges="true"

答案 2 :(得分:0)

使用动画类

fun setVisibilityWithAnimation(textView:TextView, visibility: Int) {

    if(visibility == View.VISIBLE){
        val animation = ValueAnimator.ofFloat(0.0f, 1.0f)
        animation.duration = 1000
        animation.addUpdateListener {
            textView.alpha = it.animatedValue as Float
        }
        animation.addListener(
            onStart = {
                textView.visibility = View.VISIBLE
            }
        )
    }else if (visibility == View.GONE){
        val animation = ValueAnimator.ofFloat(1.0f, 0.0f)
        animation.duration = 1000
        animation.addUpdateListener {
            textView.alpha = it.animatedValue as Float
        }
        animation.addListener(
            onEnd = {
                textView.visibility = View.GONE
            }
        )
    }
}

使用这种方式:

setVisibilityWithAnimation(labelTextView,View.GONE)