安卓为控件的VISIBLE和GONE设置动画

首先,设置动画是为了让控件的出现和消失不那么突兀;
1.编写动画代码;

 protected void setAnimation(View view) {
        TranslateAnimation translateAnimation;
        if (view.getVisibility() == View.VISIBLE) {//可见时的动画
            translateAnimation = 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);
        } else {//不可见时的动画
            translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        }
        translateAnimation.setDuration(200);
        view.setAnimation(translateAnimation);
    }

对Animation不熟的可以查询资料,这里不多做解释;
向此方法传入需要VISIBLE或者GONE的控件view,定义TranslateAnimation(平移动画),根据需要可自行更换,此处的代码为 从右向左平移出现,从左向右消失;(项目所需要的效果如此)

上下平移可更改为:(此处为从下往上平移出现,从上往下平移出现;)

 protected void setAnimation(View view) {
        TranslateAnimation translateAnimation;
        if (view.getVisibility() == View.VISIBLE) {
            translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
                    Animation.RELATIVE_TO_PARENT, 1.0f, Animation.RELATIVE_TO_PARENT, 0.0f);
        } else {
            translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
                    Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 1.0f);
        }
        translateAnimation.setDuration(200);
        view.setAnimation(translateAnimation);
    }

2.在需要显示或消失的地方调用该函数

 //点击事件
    @OnClick({R.id.favorites1, R.id.favorites2, R.id.favorites_close, R.id.balance_tv, R.id.payment_close, R.id.vip_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
				  case R.id.balance_tv://支付按钮
		                payment.setVisibility(View.VISIBLE);//显示结账页面
		                setAnimation(payment);
		                break;
		            case R.id.payment_close://取消支付按钮
		                payment.setVisibility(View.GONE);//关闭结账页面
		                setAnimation(payment);    
		                break;
		}
   	}

此处有重点,有重点,有重点!!!
setAnimation(view);必须在setvisibility之后,否则会出现乱七八糟的动画!!!

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页