在為應用設計圖標時,可能會遇到這樣的需求:圖標有舊版與新版兩種,想同時在桌面上並排顯示,方便對照效果。
一個應用本身在 AndroidManifest.xml 的 <application> 標籤中,透過 android:icon 屬性只會有一個自己的 icon。不過 Android 系統的 Intent 提供了一個 shortcut 機制,能把「啟動某個 intent 的方式」以捷徑形式儲存到桌面,並自訂對應的圖片。微信「把好友添加到桌面」的功能,背後正是用 shortcut intent 實作的。本文就借用這個機制來實現多個圖標的對比。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent shortcutIntent = new Intent(MainActivity.this, MainActivity.this.getClass());
// 原圖標
final Intent icon1 = new Intent();
icon1.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
icon1.putExtra(Intent.EXTRA_SHORTCUT_NAME, "原圖標");
icon1.putExtra(Intent.EXTRA_SHORTCUT_ICON,
BitmapFactory.decodeResource(getResources(), R.drawable.icon1));
icon1.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(icon1);
// 新圖標
final Intent icon2 = new Intent();
icon2.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
icon2.putExtra(Intent.EXTRA_SHORTCUT_NAME, "新圖標");
icon2.putExtra(Intent.EXTRA_SHORTCUT_ICON,
BitmapFactory.decodeResource(getResources(), R.drawable.icon2));
icon2.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(icon2);
}
在 AndroidManifest.xml 中補上安裝捷徑的權限:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
以微信 5.0 與 5.2 的圖標做對比,可以明顯看出 5.2 的圖標更加扁平化,色調也略深一些。透過這個 shortcut 技巧,就能在真實桌面上並排檢視不同版本的圖標設計,非常適合設計階段的視覺驗證。