編輯:關於 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 越來越受重視的當下,這些效果可以說是必備的看家本領,也是往上進階的一塊墊腳石。
從 Android 5.X 開始,官方全面換上新的設計語言 Material Design。
Google 模擬自然界中的形態變化、光線與陰影,以及紙張之間的空間層級關係,讓平面螢幕長出了真實的縱深感。


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

想深入了解 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>

Palette 的作用是從圖片中提取色彩,讓主題能動態適應當前頁面的色調。內建六種取色類型:
使用前需加入依賴:
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() 的退路。

Material Design 最重要的特徵之一,就是「擬物扁平化」——用 Z 軸的高度來表達層次。
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;
}
Android 5.X 為圖像操作加了兩個實用的新能力:著色(Tinting)與裁剪(Clipping)。
注意 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>

要使用裁剪,先自訂 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);
}
}

RecyclerView 與 CardView 的用法我在另外的篇章裡已經寫過(包含拖拽排序、側滑刪除,以及仿支付寶銀行卡的卡片效果),這裡不再重複。
過去我們用 overridePendingTransition(int inId, int outId) 為 Activity 切換加點動畫,效果聊勝於無。Android 5.X 提供了三類 Transition:
進場/退場效果有三種:
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());
共享元素的效果:

點擊後的波紋回饋,直接用系統屬性設定背景即可:
// 有邊界波紋 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" />

這個動畫讓 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();
}
});
}
}

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;
}
}
}

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>
Android 5.0 對通知做了幾項實用改進:長按通知可顯示消息來源;鎖屏狀態下也能看到通知內容。
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());
}
}

折疊式通知的關鍵是透過 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);
}
}

懸掛式(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());
}
}

通知分為三個可見性等級:
VISIBILITY_PRIVATE:僅在解鎖狀態下顯示完整內容。VISIBILITY_PUBLIC:任何情況下都完整顯示。VISIBILITY_SECRET:在 PIN/密碼等安全鎖下隱藏內容。設定只需一行:
builder.setVisibility(Notification.VISIBILITY_PUBLIC);
另外還有兩個實用方法:
builder.setColor(Color.RED); // 設定通知背景強調色 builder.setCategory(Notification.CATEGORY_MESSAGE); // 影響通知的顯示位置與行為
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);
}
}

先把主題設為 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 這一批新特性可以歸納成三條主線:
再加上 Toolbar 帶來的佈局自由度,以及 Notification 在折疊、懸掛與可見性分級上的強化,5.X 這一版的 UI 能力確實是一個分水嶺。
本章範例原始碼已託管在 GitHub 上,有興趣的讀者可以 clone 下來直接跑。
Android 圓角圓形圖片(一):使用 Xfermode 實作圓角與圓形 ImageView
實作目標本篇要建立一個可顯示圓形或圓角的 ImageView,並保留一般圖片檢視的基本行為。Xfermode 概念PorterDuff.Mode 可用來控制圖層合成方式。
ListView 中為不同按鈕綁定各自的點擊事件
當 ListView 的每一項裡有兩個以上的按鈕時,直接為它們各寫一個 OnClickListener 很快就會亂掉。比較乾淨的做法是:在 Adapter 內部綁定點擊,
Android + SSH 開發商城 App(一):數據庫建置與環境搭建
項目簡介 本系列文章示範如何用 SSH(Struts、Spring、Hibernate)打造 Android 的後端伺服器,並完成前端 App。涵蓋的技術點相當廣泛,包含
動手做一個 Android 美圖拼圖小遊戲
概述 這款小遊戲的玩法很直覺:把一張圖片切成很多份,玩家點擊交換,最終拼回一張完整的圖。這樣的設計讓關卡非常容易規劃,從 3×3、4×4、5×5、6×6 一路往上疊加即可