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

Android 5.X 新特性詳解:Material Design 從設計理念到程式碼落地

編輯:關於 Android 程式設計

本章知識點

12.1 Android 5.X UI 設計初步:材料的形態模擬、更加真實的動畫、大色塊的使用
12.2 Material Design 主題 12.3 Palette 12.4 視圖與陰影
12.5 Tinting 和 Clipping:Tinting(著色)、Clipping(裁剪)
12.6 列表與卡片:RecyclerView、CardView
12.7 Android 過渡動畫 12.8 Material Design 動畫效果:Ripple、Circular Reveal、View state changes Animation
12.9 Toolbar
12.10 Notification:基本、折疊式、懸掛式、顯示等級

前言

轉眼間 Android 7.0 都已經問世,我還在啃 5.0 的內容,心情實在有些複雜。不過這一章篇幅雖長,裡面的動畫實例確實漂亮——在 UI 越來越受重視的當下,這些效果可以說是必備的看家本領,也是往上進階的一塊墊腳石。

12.1 Android 5.X UI 設計初步

從 Android 5.X 開始,官方全面換上新的設計語言 Material Design。

12.1.1 材料的形態模擬

Google 模擬自然界中的形態變化、光線與陰影,以及紙張之間的空間層級關係,讓平面螢幕長出了真實的縱深感。

12.1.2 更加真實的動畫

12.1.3 大色塊的使用

Material Design 大量採用高飽和、適中亮度的大色塊,用來建立界面的主次層級。

想深入了解 Material Design 的讀者,可以參考官方的設計規範網站。

12.2 Material Design 主題

系統預設提供三種主題:

@android:style/Theme.Material                  (dark version)
@android:style/Theme.Material.Light            (light version)
@android:style/Theme.Material.Light.DarkActionBar

同時提出了 Color Palette 的概念,讓開發者自行定義系統各區域的配色。

透過自訂 Style 即可建立屬於自己的配色主題:

<resources>
    <!-- 繼承 Material 主題 -->
    <style name="AppTheme" parent="android:Theme.Material">
        <!-- 主要色彩,用於 App bar,也是品牌色 -->
        <item name="colorPrimary">#BEBEBE</item>
        <!-- 較深的變體,用於狀態列與情境式 App bar -->
        <item name="colorPrimaryDark">#FF5AEBFF</item>
        <!-- 控制元件配色,如 CheckBox、輸入框 -->
        <item name="colorAccent">#FFFF4130</item>
    </style>
</resources>

12.3 Palette:讓主題跟著圖片變色

Palette 的作用是從圖片中提取色彩,讓主題能動態適應當前頁面的色調。內建六種取色類型:

  • Vibrant(充滿活力)/Vibrant dark/Vibrant light
  • Muted(柔和)/Muted dark/Muted light

使用前需加入依賴:

compile 'com.android.support:palette-v7:21.0.2'

把 Bitmap 傳進去,再呼叫 Palette.generate()(同步)或 Palette.generateAsync()(非同步)即可取得 Palette 物件。以下範例示範用圖片的柔和色調同步改變狀態列與 ActionBar:

public class PaletteActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.palette);

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test);

        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                // 取柔和的深色調
                Palette.Swatch vibrant = palette.getDarkMutedSwatch();
                if (vibrant != null) {
                    getSupportActionBar().setBackgroundDrawable(
                            new ColorDrawable(vibrant.getRgb()));
                    getWindow().setStatusBarColor(vibrant.getRgb());
                }
            }
        });
    }
}

書上的原始範例在取色失敗時會出現空指標錯誤——因為某些圖片未必能產生指定色調。實務上一定要加上 null 判斷,或準備 getDarkVibrantSwatch() 到 getDarkMutedSwatch() 的退路。

12.4 視圖與陰影

Material Design 最重要的特徵之一,就是「擬物扁平化」——用 Z 軸的高度來表達層次。

12.4.1 陰影效果

Android 5.X 在传统 View 的 x、y 之外加入了 z 方向。View 的 z 值由兩部分組成:

Z = elevation + translationZ;

通常在 XML 佈局中直接設定 elevation 即可:

android:elevation="XXdp"

下面用實例比較不同高度的效果:

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

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp"
        android:background="@mipmap/ic_launcher" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp"
        android:background="@mipmap/ic_launcher"
        android:elevation="2dp" />

    <TextView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="10dp"
        android:background="@mipmap/ic_launcher"
        android:elevation="10dp" />
</LinearLayout>

程式碼中同樣可以調整:

view.setTranslationZ(xxx);

更常見的是搭配屬性動畫,讓高度平滑過渡:

if (flag) {
    view.animate().translationZ(100);
    flag = false;
} else {
    view.animate().translationZ(0);
    flag = true;
}

12.5 Tinting 和 Clipping

Android 5.X 為圖像操作加了兩個實用的新能力:著色(Tinting)與裁剪(Clipping)。

12.5.1 Tinting(著色)

注意 tint 與 tintMode 這兩個屬性的搭配:

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

    <ImageView android:layout_width="100dp" android:layout_height="100dp"
        android:layout_gravity="center" android:elevation="5dp"
        android:src="@mipmap/ic_launcher" />

    <ImageView android:layout_width="100dp" android:layout_height="100dp"
        android:layout_gravity="center" android:elevation="5dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@android:color/holo_blue_bright" />

    <ImageView android:layout_width="100dp" android:layout_height="100dp"
        android:layout_gravity="center" android:elevation="5dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@android:color/holo_blue_bright"
        android:tintMode="add" />

    <ImageView android:layout_width="100dp" android:layout_height="100dp"
        android:layout_gravity="center" android:elevation="5dp"
        android:src="@mipmap/ic_launcher"
        android:tint="@android:color/holo_blue_bright"
        android:tintMode="multiply" />
</LinearLayout>

12.5.2 Clipping(裁剪)

要使用裁剪,先自訂 ViewOutlineProvider 改寫 outline,再用 setOutlineProvider 把它套到 View 上:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_rect"
        android:layout_width="100dp" android:layout_height="100dp"
        android:layout_marginTop="20dp" android:elevation="1dp"
        android:gravity="center" />

    <TextView
        android:id="@+id/tv_circle"
        android:layout_width="100dp" android:layout_height="100dp"
        android:layout_marginTop="20dp" android:elevation="1dp"
        android:gravity="center" />
</LinearLayout>
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        View v1 = findViewById(R.id.tv_rect);
        View v2 = findViewById(R.id.tv_circle);

        // 自訂 outline:圓角矩形
        ViewOutlineProvider provider1 = new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), 30);
            }
        };

        // 自訂 outline:正圓
        ViewOutlineProvider provider2 = new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, view.getWidth(), view.getHeight());
            }
        };

        v1.setOutlineProvider(provider1);
        v2.setOutlineProvider(provider2);
    }
}

12.6 列表與卡片

RecyclerView 與 CardView 的用法我在另外的篇章裡已經寫過(包含拖拽排序、側滑刪除,以及仿支付寶銀行卡的卡片效果),這裡不再重複。

12.7 Activity 過渡動畫

過去我們用 overridePendingTransition(int inId, int outId) 為 Activity 切換加點動畫,效果聊勝於無。Android 5.X 提供了三類 Transition:

  • 進入:決定 Activity 中的視圖如何進場。
  • 退出:決定視圖如何離場。
  • 共享元素:決定兩個 Activity 之間如何共享同一個視圖。

進場/退場效果有三種:

  • explode(分解)——從螢幕中央進出,視圖飛散或聚合。
  • slide(滑動)——從螢幕邊緣滑入滑出。
  • fade(淡出)——改變不透明度來加入或移除視圖。

共享元素則有四種:

  • changeBounds——改變目標視圖的佈局邊界。
  • changeClipBounds——裁剪目標視圖的邊界。
  • changeTransform——改變縮放比例與旋轉角度。
  • changeImageTransform——改變目標圖片的大小與縮放比例。

以 ActivityA 跳到 ActivityB 為例,A 端啟動時這樣寫:

startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());

B 端則需要開啟內容轉場:

getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);

或在 B 的樣式中宣告:

<item name="android:windowContentTransitions">true</item>

接著設定進場效果:

getWindow().setEnterTransition(new Explode());
getWindow().setEnterTransition(new Slide());
getWindow().setEnterTransition(new Fade());

或離場效果:

getWindow().setExitTransition(new Explode());
getWindow().setExitTransition(new Slide());
getWindow().setExitTransition(new Fade());

三種普通切換動畫的效果:

共享元素的做法:先在 A、B 兩邊為共用視圖設定相同的 transitionName:

android:transitionName="XXX"

程式碼中,單一共享元素:

startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(
        this, view, "share").toBundle());

多個共享元素則用 Pair.create() 串起來:

startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(
        this,
        Pair.create(view, "share"),
        Pair.create(fab, "fab")).toBundle());

共享元素的效果:

12.8 Material Design 動畫效果

12.8.1 Ripple 效果

點擊後的波紋回饋,直接用系統屬性設定背景即可:

// 有邊界波紋
android:background="?android:attr/selectableItemBackground"

// 無邊界波紋
android:background="?android:attr/selectableItemBackgroundBorderless"
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_light"
    android:gravity="center"
    android:orientation="vertical">

    <Button android:layout_width="100dp" android:layout_height="100dp"
        android:background="?android:attr/selectableItemBackground"
        android:text="有界波紋" android:textColor="@android:color/white" />

    <Button android:layout_width="100dp" android:layout_height="100dp"
        android:background="?android:attr/selectableItemBackgroundBorderless"
        android:text="無界波紋" android:textColor="@android:color/white" />
</LinearLayout>

也可以自訂 ripple 資源,形狀與顏色都能控制:

<ripple xmlns:android="https://schemas.android.com/apk/res/android"
    android:color="?android:colorPrimary">
    <item>
        <shape android:shape="oval">
            <solid android:color="?android:colorAccent" />
        </shape>
    </item>
</ripple>
<Button
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:background="@drawable/ripple" />

12.8.2 Circular Reveal

這個動畫讓 View 以圓形綻開的方式揭露。核心 API 是:

public static Animator createCircularReveal(View view, int centerX, int centerY,
                                            float startRadius, float endRadius) {
    return new RevealAnimator(view, centerX, centerY, startRadius, endRadius);
}

四個參數各有含義:centerX/centerY 是動畫圓心,startRadius 是起始半徑,endRadius 是結束半徑。用法示範:

public class CircularReveal extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circular_reveal);

        final View oval = findViewById(R.id.oval);
        oval.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 從中心向外收攏消失
                Animator animator = ViewAnimationUtils.createCircularReveal(
                        oval, oval.getWidth() / 2, oval.getHeight() / 2,
                        oval.getWidth(), 0);
                animator.setInterpolator(new AccelerateDecelerateInterpolator());
                animator.setDuration(2000);
                animator.start();
            }
        });

        final View rect = findViewById(R.id.rect);
        rect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 從左上角綻開,半徑取對角線長度以覆蓋整個 View
                Animator animator = ViewAnimationUtils.createCircularReveal(
                        rect, 0, 0, 0,
                        (float) Math.hypot(rect.getWidth(), rect.getHeight()));
                animator.setInterpolator(new AccelerateInterpolator());
                animator.setDuration(2000);
                animator.start();
            }
        });
    }
}

12.8.3 View state changes Animation

StateListAnimator:過去的 selector 只能換背景色來做回饋,現在可以直接掛上動畫。在 XML 中定義並放進 selector:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <set>
            <!-- 放入 animator -->
        </set>
    </item>
    <item android:state_pressed="false">
        <set>
            <!-- 放入 animator -->
        </set>
    </item>
</selector>
<Button
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:background="@drawable/anim_change" />

要特別注意:Animator 必須顯式載入才會生效,因此要在程式碼中用 AnimatorInflater.loadStateListAnimator() 載入,再透過 View.setStateListAnimator() 掛到視圖上。


animated-selector:另一種狀態切換動畫,做法是把一串逐格圖當成動畫幀。先準備好狀態切換用的序列圖:

然後在 XML 中把這些圖片按順序編排,每格給 android:duration="16"(約 60fps),並用 state_on/state_off 標記兩個端點態:

<animated-selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:id="@+id/state_on" android:state_checked="true">
        <bitmap android:src="@drawable/ic_done_anim_030" />
    </item>
    <item android:id="@+id/state_off">
        <bitmap android:src="@drawable/ic_plus_anim_030" />
    </item>
    <item android:duration="16"><bitmap android:src="@drawable/ic_plus_anim_000" /></item>
    <item android:duration="16"><bitmap android:src="@drawable/ic_plus_anim_001" /></item>
    <!-- …… 依序補上 ic_plus_anim_002 至 030 …… -->
    <item android:duration="16"><bitmap android:src="@drawable/ic_done_anim_000" /></item>
    <item android:duration="16"><bitmap android:src="@drawable/ic_done_anim_001" /></item>
    <!-- …… 依序補上 ic_done_anim_002 至 030 …… -->
</animated-selector>

主程式只需切換狀態:

public class AnimatedSelectorActivity extends AppCompatActivity {
    private boolean mIsCheck;
    private static final int[] STATE_CHECKED   = new int[]{android.R.attr.state_checked};
    private static final int[] STATE_UNCHECKED = new int[]{};
    private ImageView mImageView;
    private Drawable mDrawable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_animated_selector);
        mImageView = (ImageView) findViewById(R.id.image);
        mDrawable = getResources().getDrawable(R.drawable.fab_anim);
        mImageView.setImageDrawable(mDrawable);
    }

    public void anim(View view) {
        if (mIsCheck) {
            mImageView.setImageState(STATE_UNCHECKED, true);
            mIsCheck = false;
        } else {
            mImageView.setImageState(STATE_CHECKED, true);
            mIsCheck = true;
        }
    }
}

12.9 Toolbar

Toolbar 與 ActionBar 最大的差別在於自由度與可控性——Toolbar 只是一個普通容器,放哪、放什麼、怎麼擺都由你決定,這也是 Google 逐步用它取代 ActionBar 的原因。

使用 Toolbar 需引入 appcompat-v7,並把主題設為 NoActionBar:

<resources>
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>           <!-- toolbar 顏色 -->
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>  <!-- 狀態列顏色 -->
        <item name="android:windowBackground">@android:color/white</item>
        <item name="android:searchViewStyle">@style/MySearchView</item>
    </style>
</resources>

12.10 Notification

Android 5.0 對通知做了幾項實用改進:長按通知可顯示消息來源;鎖屏狀態下也能看到通知內容。

12.10.1 基本 Notification

public class Notification01 extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification01);

        // 步驟一:初始化 Builder
        Notification.Builder builder = new Notification.Builder(this);

        // 步驟二:建立點擊後的 Intent 與 PendingIntent
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com"));
        PendingIntent pendingIntent = PendingIntent.getActivities(
                this, 0, new Intent[]{intent}, 0);

        // 步驟三:設定各項內容
        builder.setSmallIcon(R.mipmap.ic_launcher)
               .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
               .setContentIntent(pendingIntent)
               .setAutoCancel(true)
               .setContentTitle("Title")
               .setContentText("內容")
               .setSubText("text");

        // 步驟四:透過 NotificationManager 發出
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(0, builder.build());
    }
}

12.10.2 折疊式 Notification

折疊式通知的關鍵是透過 RemoteViews 分別指定「收合時」與「展開時」的自訂視圖:

public class Notification02 extends AppCompatActivity {
    private static final int NOTIFICATION_ID_COLLAPSE = 0x01;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification02);

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.sina.com"));
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher)
               .setContentIntent(pendingIntent)
               .setAutoCancel(true)
               .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

        // 收合狀態的自訂視圖
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
        contentView.setTextViewText(R.id.textView, "show me when collapsed");

        Notification notification = builder.build();
        notification.contentView = contentView;

        // 展開狀態的自訂視圖
        RemoteViews expandedView = new RemoteViews(getPackageName(), R.layout.notification_expanded);
        notification.bigContentView = expandedView;

        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(NOTIFICATION_ID_COLLAPSE, notification);
    }
}

12.10.3 懸掛式 Notification

懸掛式(Heads-up)通知的重點是設定較高的 priority 並搭配 setFullScreenIntent:

public class Notification03 extends AppCompatActivity {
    private static final int NOTIFICATION_ID_HEADSUP = 0x01;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification03);

        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setPriority(Notification.PRIORITY_HIGH)
                .setCategory(Notification.CATEGORY_MESSAGE)
                .setContentTitle("Heads-up Notification")
                .setContentText("I am a Heads-up notification.");

        Intent push = new Intent();
        push.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        push.setClass(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, push, PendingIntent.FLAG_CANCEL_CURRENT);

        builder.setContentText("Heads-Up Notification on Android 5.0")
               .setFullScreenIntent(pendingIntent, true);

        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.notify(NOTIFICATION_ID_HEADSUP, builder.build());
    }
}

12.10.4 顯示等級的 Notification

通知分為三個可見性等級:

  • VISIBILITY_PRIVATE:僅在解鎖狀態下顯示完整內容。
  • VISIBILITY_PUBLIC:任何情況下都完整顯示。
  • VISIBILITY_SECRET:在 PIN/密碼等安全鎖下隱藏內容。

設定只需一行:

builder.setVisibility(Notification.VISIBILITY_PUBLIC);

另外還有兩個實用方法:

builder.setColor(Color.RED);                              // 設定通知背景強調色
builder.setCategory(Notification.CATEGORY_MESSAGE);       // 影響通知的顯示位置與行為

經典代碼回顧

案例一:Android 5.X 切換動畫

ActivityA 的佈局,注意 transitionName 放在哪個 View 上:

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

    <Button android:layout_width="match_parent" android:layout_height="100dp"
        android:onClick="explode" android:text="explode" />
    <Button android:layout_width="match_parent" android:layout_height="100dp"
        android:onClick="slide" android:text="slide" />
    <Button android:layout_width="match_parent" android:layout_height="100dp"
        android:onClick="fade" android:text="fade" />>
    <Button android:layout_width="match_parent" android:layout_height="100dp"
        android:transitionName="share" android:onClick="share" android:text="share" />
    <Button android:id="@+id/fab_button"
        android:layout_width="56dp" android:layout_height="56dp"
        android:transitionName="fab"
        android:background="@drawable/ripple_round" android:elevation="5dp" />
</LinearLayout>

ActivityB 的佈局,共享元素用相同的 transitionName 配對:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <View android:id="@+id/holder_view"
        android:layout_width="match_parent" android:layout_height="300dp"
        android:transitionName="share"
        android:background="?android:colorPrimary" />

    <Button android:id="@+id/fab_button"
        android:layout_width="56dp" android:layout_height="56dp"
        android:transitionName="fab"
        android:background="@drawable/ripple_round" android:elevation="5dp"
        android:layout_below="@+id/holder_view"
        android:layout_marginTop="-26dp"
        android:layout_alignParentEnd="true" />
</RelativeLayout>
public class TransitionsA extends Activity {
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transition);
    }

    public void explode(View view) {
        intent = new Intent(this, TransitionsB.class);
        intent.putExtra("flag", 0);
        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
    }

    public void slide(View view) {
        intent = new Intent(this, TransitionsB.class);
        intent.putExtra("flag", 1);
        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
    }

    public void fade(View view) {
        intent = new Intent(this, TransitionsB.class);
        intent.putExtra("flag", 2);
        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this).toBundle());
    }

    public void share(View view) {
        View fab = findViewById(R.id.fab_button);
        intent = new Intent(this, TransitionsB.class);
        intent.putExtra("flag", 3);
        // 多個共享元素用 Pair.create 串接
        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(
                this,
                Pair.create(view, "share"),
                Pair.create(fab, "fab")).toBundle());
    }
}
public class TransitionsB extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);

        int flag = getIntent().getExtras().getInt("flag");
        switch (flag) {
            case 0:
                getWindow().setEnterTransition(new Explode());
                break;
            case 1:
                getWindow().setEnterTransition(new Slide());
                break;
            case 2:
                getWindow().setEnterTransition(new Fade());
                getWindow().setExitTransition(new Fade());
                break;
            case 3:
                break;
        }
        setContentView(R.layout.activity_transition_to);
    }
}

案例二:Toolbar 的使用

先把主題設為 NoActionBar,然後在佈局中聲明 Toolbar。接著在 menu 資料夾建立選單 XML:

<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item android:id="@+id/ab_search"
        android:orderInCategory="80"
        android:title="action_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_share"
        android:orderInCategory="90"
        android:title="action_share"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="action_settings"
        app:showAsAction="never" />
</menu>
public class ToolbarActivity extends AppCompatActivity {
    private ShareActionProvider mShareActionProvider;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toolbar);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setLogo(R.mipmap.ic_launcher);
        toolbar.setTitle("主標題");
        toolbar.setSubtitle("副標題");
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }
}

再加上一層 DrawerLayout,就能做出側滑菜單。注意側滑內容必須指定水平方向的 layout_gravity="start":

public class ToolbarActivity extends AppCompatActivity {
    private ShareActionProvider mShareActionProvider;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_toolbar);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setLogo(R.mipmap.ic_launcher);
        toolbar.setTitle("主標題");
        toolbar.setSubtitle("副標題");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar,
                R.string.abc_action_bar_home_description,
                R.string.abc_action_bar_home_description_format);
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(
                menu.findItem(R.id.action_share));
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/*");
        mShareActionProvider.setShareIntent(intent);
        return super.onCreateOptionsMenu(menu);
    }
}

本章回顧

Android 5.X 這一批新特性可以歸納成三條主線:

  • 視覺層次:Z 軸(elevation/translationZ)、陰影、Tinting 與 Clipping,讓界面從平面走向有厚度的層次表達。
  • 色彩系統:Material 主題的三個 colorPrimary 系列屬性,加上 Palette 的動態取色,讓配色從「寫死」變成「隨內容變化」。
  • 動效:Activity 過渡動畫(explode/slide/fade 與共享元素)、Ripple、Circular Reveal、StateListAnimator,讓操作回饋從靜態換色升級為連續的動態語言。

再加上 Toolbar 帶來的佈局自由度,以及 Notification 在折疊、懸掛與可見性分級上的強化,5.X 這一版的 UI 能力確實是一個分水嶺。

本章範例原始碼已託管在 GitHub 上,有興趣的讀者可以 clone 下來直接跑。

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