我正在使用我的应用中的一些图片制作相对布局的动画。当我编写代码以在按钮单击时为布局设置动画,这是第一次显示不是动画。然后在同一个按钮上单击我向上滑动布局。之后,如果我单击按钮滑动动画工作正常。实际上我必须在onCreate本身而不是按钮点击内写下这个滑动动画。以下是我的代码。谁能告诉我为什么它没有显示动画?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fadeview);
iconLayout=(RelativeLayout)findViewById(R.id.icon_ayout);
iconLayout.postDelayed(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
iconLayout.setVisibility(View.VISIBLE);
SlideToDown();
}
}, 500);
}
public void SlideToAbove() {
Animation slide = null;
slide=new TranslateAnimation(0.0f, 0.0f, 0.0f,-iconLayout.getHeight());
slide.setDuration(1000);
slide.setFillAfter(true);
slide.setFillEnabled(true);
iconLayout.startAnimation(slide);
slide.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
iconLayout.clearAnimation();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
iconLayout.getWidth(), iconLayout.getHeight());
// lp.setMargins(0, 0, 0, 0);
//lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
iconLayout.setLayoutParams(lp);
}
});
}
public void SlideToDown() {
Animation slide = null;
slide=new TranslateAnimation(0.0f, 0.0f, -iconLayout.getHeight(), 0.0f);
slide.setDuration(1000);
slide.setFillAfter(true);
slide.setFillEnabled(true);
iconLayout.startAnimation(slide);
slide.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
iconLayout.clearAnimation();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
iconLayout.getWidth(), iconLayout.getHeight());
lp.setMargins(0,0, 0, 0);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
iconLayout.setLayoutParams(lp);
}
});
}
答案 0 :(得分:0)
这是因为你在onCreate()中开始动画,并且此时视图可用,但实际上并没有绘制(没有宽度和高度)。这里iconLayout.getHeight()
的值将返回值0.
解决方案是将Layoutlistener设置为视图,并且侦听器在绘制时会告诉您。之后,您可以开始动画。
ViewTreeObserver loadingObserver = iconLayout.getViewTreeObserver();
loadingObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
iconLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
SlideToDown();
}
});