第一步:首先在xml佈局文件中設置該控件爲android:visibility="gone"。
第二步:在代碼中配置兩個Animation
alphaAnimation appearAnimation = new AlphaAnimation(0, 1);
appearAnimation.setDuration(500);
disappearAnimation = new AlphaAnimation(1, 0);
disappearAnimation.setDuration(500);
</pre> 第三步:想讓控件出現時</p><p><pre name="code" class="java">if (flowBottomLL.getVisibility() == View.GONE) {
flowBottomLL.startAnimation(appearAnimation);
flowBottomLL.setVisibility(View.VISIBLE);
}
第四步:想讓控件消失時,
</pre></p><p></p><p></p><pre name="code" class="java">flowBottomLL.startAnimation(disappearAnimation);
disappearAnimation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
flowBottomLL.setVisibility(View.GONE);
}
});
總結:出現和消失的代碼是不同的,因爲我們的控件一開始是隱藏的,當執行出現的動畫時,如果不立即設置控件爲可見,就看不到這個動畫效果;同樣,在消失的時候,不能馬上隱藏控件,那樣也會看不到動畫效果,必須監聽動畫的執行,當動畫執行完成後,再設置控件隱藏。本文只提到如何讓控件逐漸出現和消失,並沒有提到如何觸發這兩個效果,我提供一種情況吧。如果要達到觸摸屏幕,控件就逐漸出現,手離開屏幕若干秒後,控件就逐漸消失的效果,可以重寫onTouchEvent()
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//讓控件出現
}
if (event.getAction() == MotionEvent.ACTION_UP) {
isFlowing = false;
if (flowBottomLL.getVisibility() == View.VISIBLE) {
Message msg = handler.obtainMessage(1);
currentTime = System.currentTimeMillis(); //用時間來設置標誌位,在handleMessage方法中判斷觸發事件的來源是否是同一個.
Bundle bundle = new Bundle();
bundle.putLong("currentTime", currentTime);
msg.setData(bundle);
handler.sendMessageDelayed(msg, 3000);
}<pre name="code" class="java">} return super.onTouchEvent(event); }
在Handler中:
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
if (!isFlowing && msg.getData().getLong("currentTime") == currentTime) {
flowBottomLL.startAnimation(disappearAnimation);
disappearAnimation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {
flowBottomLL.setVisibility(View.GONE);
}
});
}
}
}
};