Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用屬性動畫實現布局的下拉展開與收起效果

編輯:關於 Android 程式設計

從 Android 3.0 開始,Google 引入了屬性動畫(Property Animation)框架,讓我們能做出更豐富、更可控的動畫,於是趁這個需求聊一下。

需求是這樣:點擊一個 View 時,把下方隱藏的 View 展開顯示。直覺做法是切換 visibility 從 GONE 到 VISIBLE,但那是瞬間切換,沒有過渡,看起來很生硬。屬性動畫就是更好的方案——既然要動的是「高度」,那就讓高度從 0 平滑增加到目標值。

收起的狀態:

展開的狀態:

點擊箭頭即可在兩者間切換。

布局

三個線性布局堆疊:標題、固定內容、待展開的內容(android:id="@+id/linear_hidden"),最下方是一個帶 onClick 的箭頭列。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.ltl.mpiggybank.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#458EFD"
        android:padding="10dip">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="下拉展開動畫"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#548AEA"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dip"
            android:text="昨日收益(元)"
            android:textColor="#ffffff"
            android:textSize="16sp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0.00"
            android:textColor="#ffffff"
            android:textSize="45sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linear_hidden"
        android:layout_width="match_parent"
        android:layout_height="120dip"
        android:background="#548AEA"
        android:gravity="center"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dip"
            android:text="顯示的View"
            android:textColor="#ffffff"
            android:textSize="16sp" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0.00"
            android:textColor="#ffffff"
            android:textSize="35sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#548AEA"
        android:gravity="center"
        android:onClick="onClick"
        android:orientation="vertical">
        <ImageView
            android:id="@+id/my_iv"
            android:layout_width="25dip"
            android:layout_height="25dip"
            android:layout_margin="20dip"
            android:src="@drawable/scroll" />
    </LinearLayout>
</LinearLayout>

關鍵是算出目標高度。布局裡寫的是 120dp,執行時必須換成像素,否則不同螢幕密度下動畫幅度會跑掉:

mDensity = getResources().getDisplayMetrics().density;
mHiddenViewMeasuredHeight = (int) (mDensity * 120 + 0.5);

用 ValueAnimator 驅動高度

讓高度在兩個數值之間插值,每次更新就寫回 LayoutParams:

ValueAnimator animator = ValueAnimator.ofInt(start, end);
animator.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator arg0) {
        int value = (int) arg0.getAnimatedValue();
        ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
        layoutParams.height = value;
        v.setLayoutParams(layoutParams);
    }
});

完整程式碼

public class MainActivity extends ActionBarActivity {

    private LinearLayout mHiddenLayout;
    private float mDensity;
    private int mHiddenViewMeasuredHeight;
    private ImageView mIv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        mHiddenLayout = (LinearLayout) findViewById(R.id.linear_hidden);
        mIv = (ImageView) findViewById(R.id.my_iv);
        mDensity = getResources().getDisplayMetrics().density;
        mHiddenViewMeasuredHeight = (int) (mDensity * 120 + 0.5);
    }

    public void onClick(View v) {
        if (mHiddenLayout.getVisibility() == View.GONE) {
            animateOpen(mHiddenLayout);
            animationIvOpen();
        } else {
            animateClose(mHiddenLayout);
            animationIvClose();
        }
    }

    private void animateOpen(View v) {
        v.setVisibility(View.VISIBLE);
        createDropAnimator(v, 0, mHiddenViewMeasuredHeight).start();
    }

    private void animateClose(final View view) {
        ValueAnimator animator = createDropAnimator(view, view.getHeight(), 0);
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                // 收起完成後才設為 GONE,避免高度為 0 卻仍佔位
                view.setVisibility(View.GONE);
            }
        });
        animator.start();
    }

    private ValueAnimator createDropAnimator(final View v, int start, int end) {
        ValueAnimator animator = ValueAnimator.ofInt(start, end);
        animator.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator arg0) {
                int value = (int) arg0.getAnimatedValue();
                ViewGroup.LayoutParams layoutParams = v.getLayoutParams();
                layoutParams.height = value;
                v.setLayoutParams(layoutParams);
            }
        });
        return animator;
    }

    private void animationIvOpen() {
        RotateAnimation animation = new RotateAnimation(0, 180,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setFillAfter(true);
        animation.setDuration(100);
        mIv.startAnimation(animation);
    }

    private void animationIvClose() {
        RotateAnimation animation = new RotateAnimation(180, 0,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setFillAfter(true);
        animation.setDuration(100);
        mIv.startAnimation(animation);
    }
}

兩個細節值得留意:展開前要先設 VISIBLE 再從 0 開始動畫,收起則要在動畫結束後才設 GONE,順序顛倒就會出現閃跳。另外每次改 LayoutParams.height 都會觸發重新測量與布局,動畫時間別拉太長;若列表中有大量這類效果,改用 ViewAnimationUtils.createCircularReveal 或 Transition 框架會更省效能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved