更改高度后,我的视图不可见

时间:2018-11-12 17:01:14

标签: android

 private boolean isOffersHidden = false; 



findViewById(R.id.imgHideOffers).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Animation animationOffers;

            if(!isOffersHidden){
                animationOffers = AnimationUtils.loadAnimation(MainActivity.this, R.anim.right_side);
                findViewById(R.id.lyOfffersContainer).setAnimation(animationOffers);
                findViewById(R.id.lyOfffersContainer).startAnimation(animationOffers);


                reduceHeight(findViewById(R.id.lyOfffersContainer));

                isOffersHidden = true;
            }else{
                animationOffers = AnimationUtils.loadAnimation(MainActivity.this, R.anim.appear_offers);
                findViewById(R.id.lyOfffersContainer).setAnimation(animationOffers);
                findViewById(R.id.lyOfffersContainer).startAnimation(animationOffers);

                increaseHeight(findViewById(R.id.lyOfffersContainer));

                isOffersHidden = false;
            }

        }

    });

  //Im using this piece of code to reduce my view height:

  private void reduceHeight(final View v) {

    ValueAnimator va = ValueAnimator.ofInt(v.getHeight(), 0);
    va.setDuration(1500);
    va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        public void onAnimationUpdate(ValueAnimator animation) {
            v.getLayoutParams().height = (Integer) animation.getAnimatedValue();
            v.requestLayout();
        }
    });

    va.start();
}


//Im using this code to increase my view height:

private void increaseHeight(final View v){

    ValueAnimator va = ValueAnimator.ofInt(0, 220);
    va.setDuration(1500);
    va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        public void onAnimationUpdate(ValueAnimator animation) {
            v.getLayoutParams().height = (Integer) animation.getAnimatedValue();
            v.requestLayout();
        }
    });

    va.start();
}

当我减小视图高度时,一切正常,但是当我再次尝试增大高度时,它变得不可见:

普通视图:

enter image description here

减小和增加视图高度后

enter image description here

我希望您能理解我的问题,我不是以编程方式将视图设置为不可见,如何解决此问题?

1 个答案:

答案 0 :(得分:0)

是的,问题出在您的onClick函数上。 reduceHeightincreaseHeight需要时间来补充。在代码中,如果单击得足够快,将并行运行2个进程(减少和增加)。这会使您的onClick函数不可靠。要修复此问题,您应该在启动新动画之前取消动画师,例如:

ValueAnimator va = null; // make this animator global
private void reduceHeight(final View v) {
if(va != null) va.end(); // end the running animation; you should call this in the increaseHeight function as well. 
va = ValueAnimator.ofInt(v.getHeight(), 0);
va.setDuration(1500);
va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    public void onAnimationUpdate(ValueAnimator animation) {
        v.getLayoutParams().height = (Integer) animation.getAnimatedValue();
        v.requestLayout();
        //remember to set va = null when animation ends.
    }
});
va.start();
}