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

Android 版面變化的動畫效果(一):animateLayoutChanges 屬性快速上手

編輯:關於 Android 程式設計

本篇示範最省事的做法:在版面容器上打開 android:animateLayoutChanges 屬性,往裡頭加 View 時就會自動帶入過場動畫,切換不至于太過生硬。

操作情境是:點擊 TextView 時,為 LinearLayout 動態添加一個按鈕。因為我們在容器上設了 android:animateLayoutChanges="true",這個新增動作就有了動畫。

要注意的是,這只是系統預設的動畫效果。若想自訂,就得改用屬性動畫,那會是下一篇的主題。

MainActivity 如下:

package cc.test;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Demo 描述:版面變化時動畫效果的實現(一)
 * 主要是測試版面中的 animateLayoutChanges 屬性。
 *
 * 示例描述:
 * 點擊 TextView 時為線性版面添加按鈕。
 * 為了讓添加按鈕時有動畫效果,我們給線性版面設定了
 * android:animateLayoutChanges="true"
 * 往版面中添加 View 時就會有預設的動畫效果。
 *
 * 若需要自定義動畫效果,則需要用到屬性動畫,
 * 請參見下一篇:版面變化時動畫效果的實現(二)
 */
public class TestAnimateLayoutChangesActivity extends Activity {
    private LinearLayout mRootLinearLayout;
    private Context mContext;
    private TextView mTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init(){
        mContext = this;
        mRootLinearLayout = (LinearLayout) findViewById(R.id.rootLinearLayout);
        mTextView = (TextView) findViewById(R.id.textView);
        mTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Button button = new Button(mContext);
                button.setText("button");
                mRootLinearLayout.addView(button);
            }
        });
    }
}

main.xml 如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rootLinearLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:animateLayoutChanges="true">

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="測試版面中的 animateLayoutChanges 屬性\n注意測試環境為 Android 4.0" />
</LinearLayout>

參考資料:
1 https://developer.android.com/training/animation/layout.html
2 https://blog.csdn.net/think_soft/article/details/12417107

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