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

屬性動畫玩出花:打造一個有呼吸感的 Android 登錄界面

編輯:關於 Android 程式設計

登錄界面大概是每個 Android 開發者都寫過的頁面。輸入賬號、輸入密碼、點擊登錄,功能上毫無難度。

但如果想讓它「不那麼普通」,就需要在過場動畫上下功夫了。先看效果:

(圖片是為了說明效果勉強插入的,尺寸和編輯框對不齊,湊合看。)

整體思路

用戶輸入完賬號密碼,點擊登錄後:

1. 輸入框區域緩慢收攏、淡出;
2. 收攏動畫結束的那一刻,切換到進度加載界面,並播放一個彈性放大動畫。

兩個動畫首尾相接,形成「輸入 → 加載」的自然過渡。核心技術點是 Android 的屬性動畫(Property Animation)。

一、主布局 activity_main.xml

<RelativeLayout 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:background="#7adfb8"
    tools:context=".MainActivity" >

    <include android:id="@+id/main_title" layout="@layout/title_layout" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/main_title"
        android:orientation="vertical" >
        <ImageView
            android:layout_width="55dip"
            android:layout_height="55dip"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/project_detail_cir" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dip"
            android:gravity="center"
            android:text="FIREFLY FOREST"
            android:textColor="#ffffff"
            android:textSize="24sp" />
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="SHOW YOUR IDEAS"
            android:textColor="#ffffff"
            android:textSize="16sp" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" >
        <include
            android:id="@+id/input_layout"
            android:layout_width="match_parent"
            android:layout_height="130dip"
            layout="@layout/input_layout" />
        <include
            android:id="@+id/layout_progress"
            android:layout_width="match_parent"
            android:layout_height="130dip"
            layout="@layout/layout_progress"
            android:visibility="gone" />
        <TextView
            android:id="@+id/main_btn_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/input_layout"
            android:layout_centerInParent="true"
            android:layout_marginTop="15dip"
            android:background="@drawable/text_bg"
            android:gravity="center"
            android:paddingBottom="2dip"
            android:paddingLeft="15dip"
            android:paddingRight="15dip"
            android:paddingTop="2dip"
            android:text="Login"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </RelativeLayout>
</RelativeLayout>

注意這裡的關鍵設計:input_layout 和 layout_progress 用 include 引入,且高度都設為 130dip,這樣兩者可以完全重疊佔位,切換時不會引起界面跳動。進度層初始設為 gone。

二、子布局文件

標題欄 title_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dip"
    android:gravity="center_vertical"
    android:padding="10dip" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/back" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ffffff"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:textSize="20sp"
        android:text="Sign up" />
</RelativeLayout>

輸入區 input_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dip"
        android:background="@drawable/radius_drawable_bg"
        android:orientation="vertical"
        android:padding="10dip" >
        <LinearLayout
            android:id="@+id/input_layout_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal" >
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/paw_code" />
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dip"
                android:background="#00000000"
                android:hint="賬號/用戶名/郵箱"
                android:padding="5dip"
                android:textSize="16sp" />
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:layout_marginBottom="5dip"
            android:layout_marginTop="5dip"
            android:background="#eeeeee" />
        <LinearLayout
            android:id="@+id/input_layout_psw"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal" >
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/paw_left" />
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dip"
                android:background="#00000000"
                android:hint="密碼"
                android:inputType="textPassword"
                android:padding="5dip"
                android:textSize="16sp" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

加載區 layout_progress.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="20dip"
        android:background="@drawable/rotate_layout_bg"
        android:orientation="vertical"
        android:padding="10dip" >
        <ProgressBar
            android:id="@+id/progressBar2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dip" />
    </LinearLayout>
</LinearLayout>

三、四個 shape 背景

輸入框的圓角矩形背景 radius_drawable_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android" >
    <corners android:radius="5dip"/>
    <solid android:color="#ffffff"/>
</shape>

進度區的白色圓形背景 rotate_layout_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="oval" >
    <corners android:radius="60dip" />
    <solid android:color="#ffffff" />
</shape>

登錄按鈕的描邊背景 text_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android" >
    <corners android:radius="50dip"/>
    <stroke android:width="1dip" android:color="#ffffff" />
</shape>

順帶說明:shape="oval" 配合足夠大的 corners 半徑,就能畫出正圓;而 stroke 只描邊不填充,適合做「幽靈按鈕」效果。這幾個都是 shape drawable 的基礎用法,比切圖靈活得多。

四、初始化控件

private TextView mBtnLogin;
private View progress;
private View mInputLayout;
private float mWidth, mHeight;
private LinearLayout mName, mPsw;

private void initView() {
    mBtnLogin = (TextView) findViewById(R.id.main_btn_login);
    progress = findViewById(R.id.layout_progress);
    mInputLayout = findViewById(R.id.input_layout);
    mName = (LinearLayout) findViewById(R.id.input_layout_name);
    mPsw = (LinearLayout) findViewById(R.id.input_layout_psw);
    mBtnLogin.setOnClickListener(this);
}

五、收攏動畫

/**
 * 輸入框的動畫效果
 *
 * @param view 目標控件
 * @param w    寬
 * @param h    高
 */
private void inputAnimator(final View view, float w, float h) {
    AnimatorSet set = new AnimatorSet();

    // 動畫一:動態收窄左右 margin,製造「向中心收攏」的錯覺
    ValueAnimator animator = ValueAnimator.ofFloat(0, w);
    animator.addUpdateListener(new AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float value = (Float) animation.getAnimatedValue();
            ViewGroup.MarginLayoutParams params =
                    (ViewGroup.MarginLayoutParams) view.getLayoutParams();
            params.leftMargin = (int) value;
            params.rightMargin = (int) value;
            view.setLayoutParams(params);
        }
    });

    // 動畫二:X 軸縮放
    ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout, "scaleX", 1f, 0.5f);

    set.setDuration(1000);
    set.setInterpolator(new AccelerateDecelerateInterpolator());
    set.playTogether(animator, animator2);
    set.start();

    set.addListener(new AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) { }

        @Override
        public void onAnimationRepeat(Animator animation) { }

        @Override
        public void onAnimationEnd(Animator animation) {
            // 動畫結束後:先顯示加載動畫,再隱藏輸入框
            progress.setVisibility(View.VISIBLE);
            progressAnimator(progress);
            mInputLayout.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAnimationCancel(Animator animation) { }
    });
}

這段代碼涉及幾個知識點:AnimatorSet 組合動畫、ValueAnimator 手動驅動屬性、ObjectAnimator 直接操作對象屬性、插值器,以及通過 AnimatorListener 串聯動畫序列。

為什麼收攏要用「改 margin」而不是直接改寬度?因為改 LayoutParams 的 margin 能讓周圍元素跟著重排,視覺上是「周圍的空間向內壓縮」;單純改寬度只會讓控件自己變窄,邊界突兀。這是一個很值得借鑒的小技巧。

六、彈性出現動畫

/**
 * 出現進度動畫
 */
private void progressAnimator(final View view) {
    PropertyValuesHolder animatorX = PropertyValuesHolder.ofFloat("scaleX", 0.5f, 1f);
    PropertyValuesHolder animatorY = PropertyValuesHolder.ofFloat("scaleY", 0.5f, 1f);
    ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(view, animatorX, animatorY);
    animator.setDuration(1000);
    animator.setInterpolator(new JellyInterpolator());
    animator.start();
}

套路相同,但這裡換成了自定義插值器。

JellyInterpolator.java:

public class JellyInterpolator extends LinearInterpolator {
    private float factor;

    public JellyInterpolator() {
        this.factor = 0.15f;
    }

    @Override
    public float getInterpolation(float input) {
        return (float) (Math.pow(2, -10 * input)
                * Math.sin((input - factor / 4) * (2 * Math.PI) / factor) + 1);
    }
}

這是一個典型的「彈簧/回聲」型插值器:指數衰減疊加正弦波,讓進度在放大到 1.0 之後還有幾次越沖與回彈,最後收斂。视觉上比線性插值生動得多。

七、串起整個流程

public class MainActivity extends Activity implements OnClickListener {

    private TextView mBtnLogin;
    private View progress;
    private View mInputLayout;
    private float mWidth, mHeight;
    private LinearLayout mName, mPsw;

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

    private void initView() {
        mBtnLogin = (TextView) findViewById(R.id.main_btn_login);
        progress = findViewById(R.id.layout_progress);
        mInputLayout = findViewById(R.id.input_layout);
        mName = (LinearLayout) findViewById(R.id.input_layout_name);
        mPsw = (LinearLayout) findViewById(R.id.input_layout_psw);
        mBtnLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 計算出控件的寬與高
        mWidth = mBtnLogin.getMeasuredWidth();
        mHeight = mBtnLogin.getMeasuredHeight();
        // 隱藏輸入框的兩行
        mName.setVisibility(View.INVISIBLE);
        mPs.setVisibility(View.INVISIBLE);
        inputAnimator(mInputLayout, mWidth, mHeight);
    }

    private void inputAnimator(final View view, float w, float h) {
        AnimatorSet set = new AnimatorSet();
        ValueAnimator animator = ValueAnimator.ofFloat(0, w);
        animator.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                ViewGroup.MarginLayoutParams params =
                        (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                params.leftMargin = (int) value;
                params.rightMargin = (int) value;
                view.setLayoutParams(params);
            }
        });
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout, "scaleX", 1f, 0.5f);
        set.setDuration(1000);
        set.setInterpolator(new AccelerateDecelerateInterpolator());
        set.playTogether(animator, animator2);
        set.start();
        set.addListener(new AnimatorListener() {
            @Override public void onAnimationStart(Animator animation) { }
            @Override public void onAnimationRepeat(Animator animation) { }
            @Override public void onAnimationEnd(Animator animation) {
                progress.setVisibility(View.VISIBLE);
                progressAnimator(progress);
                mInputLayout.setVisibility(View.INVISIBLE);
            }
            @Override public void onAnimationCancel(Animator animation) { }
        });
    }

    private void progressAnimator(final View view) {
        PropertyValuesHolder animatorX = PropertyValuesHolder.ofFloat("scaleX", 0.5f, 1f);
        PropertyValuesHolder animatorY = PropertyValuesHolder.ofFloat("scaleY", 0.5f, 1f);
        ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(view, animatorX, animatorY);
        animator.setDuration(1000);
        animator.setInterpolator(new JellyInterpolator());
        animator.start();
    }
}

幾點改進建議

1. 動畫时长偏長。1000ms 在真實產品裡偏慢,登錄這種高頻操作建議控制在 300–500ms,否則用戶會覺得卡。Material Design 建議小範圍過場用 200–300ms。

2. 用 AnimatorListenerAdapter 替代 AnimatorListener。後者是抽象類,實現時必須寫四個空方法,非常囉嗦。改成 AnimatorListenerAdapter 只需重寫 onAnimationEnd。

3. 點擊後應立即禁用按鈕。示例中動畫播放期間按鈕仍可點擊,會觸發多次動畫。記得 setEnabled(false),動畫結束或請求失敗後再恢復。

4. 加載動畫需要一個結束出口。示例只演示了「出現」,真實場景中網絡請求返回後必須調用 progress.setVisibility(View.GONE) 並給出結果反饋,否則用戶會永遠卡在加載態。

5. 若使用 ConstraintLayout,可以更優雅。把 input_layout 與 layout_progress 的切換改成 TransitionManager.beginDelayedTransition 加可見性切換,系統會自動生成淡入淡出,無需手寫 AnimatorSet。

屬性動畫的強大之處在於:它把「變化」抽象成了對象屬性的連續演進,插值器決定演進曲線,監聽器決定演進之後做什麼。理解了這個模型,各種炫酷過場都能自己拼出來。

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