實體 Menu 鍵正逐漸退出歷史舞台(可參考 Android 官方 “Say Goodbye to the Menu button”),但 Menu 的功能並未消失,反而在 Action Bar 上獲得更寬廣的發展空間。自訂 Menu 的通用做法,是用自訂的 PopupWindow 或 AlertDialog 取代傳統 Menu。本文採用 ActionProvider + PopupWindow,這也是 Google 官方推薦的方式。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
menu 版面 main.xml:
<menu xmlns:android="https://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="ifRoom"
android:actionProviderClass="com.lichen.remind.actionbar.BlinkActionProvider"
android:title="@string/action_settings"/>
</menu>
關鍵是 android:actionProviderClass,它把這個選單項的呈現與行為完全交給自訂的 Provider。
blink_action_provider.xml 就是實際顯示在選單位置上的內容,這裡只是一張圖片,後續會動態掛上 PopupWindow:
<?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="match_parent" >
<ImageView android:id="@+id/menu_blink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/menu_blink"/>
</RelativeLayout>
public class BlinkActionProvider extends ActionProvider implements OnClickListener {
private Context mContext;
private LayoutInflater mLayoutInflater;
private PopupWindow mPopWindow;
// 注意:建構子必須呼叫 super(context)
public BlinkActionProvider(Context context) {
super(context);
mContext = context;
}
@Override
@Deprecated
public View onCreateActionView() {
mLayoutInflater = LayoutInflater.from(mContext);
View rootView = mLayoutInflater.inflate(R.layout.blink_action_provider, null);
ImageView menuBlink = (ImageView) rootView.findViewById(R.id.menu_blink);
menuBlink.setBackgroundResource(R.drawable.blink_menu);
menuBlink.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View view) {
/** 建立自訂 PopupWindow */
ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(
R.layout.fragment_about_me, null, true);
mPopWindow = new PopupWindow(menuView, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, true);
mPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mPopWindow.setOutsideTouchable(true); // 觸摸外面時消失
mPopWindow.setAnimationStyle(android.R.style.Animation_Dialog); // dialog 動畫
mPopWindow.showAsDropDown(view); // 顯示在錨點 view 的左下方
/** PopupWindow 內 TextView 的點擊事件 */
TextView tv = (TextView) menuView.findViewById(R.id.about_me);
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(mContext, "點擊了 BlinkMenu", Toast.LENGTH_SHORT).show();
mPopWindow.dismiss();
}
});
}
}
幾個實作細節值得注意:建構子一定要呼叫 super(context),否則會在 inflate 時崩潰;onCreateActionView() 已標記為 Deprecated,新專案可改為覆寫 onCreateActionView(MenuItem);若要更進一步,可搭配 onCreateView() 回傳自訂 View 並實作 onPrepareSubMenu 處理狀態同步。
最後談談設計而非技術:Menu 的消亡不是功能退步,而是互動模式從「隱藏式選單」走向「可見的操作列」。真正好的設計來自對平台演進方向的理解,而不是把幾張圖 PS 進 Action Bar。