Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 中階開發

換掉系統選單的樣子:攔截 IconMenuItemView 自訂背景

編輯:中階開發

Android 的 OptionsMenu 預設長相是系統說了算,想換背景圖只能繞一條路:攔截版面膨脹的過程,把選單項目本身的 View 換成我們自己處理過的物件。做法關鍵在 LayoutInflater.Factory。

整體思路

在 onCreateOptionsMenu() 完成 inflate 之後,呼叫 setMenuBackground(),透過 getLayoutInflater().setFactory() 註冊一個自訂 Factory。當系統試圖建立 com.android.internal.view.menu.IconMenuItemView 時,我們就接手,先用 createView() 產生原本該有的 View,再用 Handler.post() 延後一個訊框去設定背景圖。

為什麼要延後?因為在 Factory.onCreateView() 當下直接設定背景,往往會被後續的樣式套用蓋掉;丟到下一輪訊息迴圈處理,設定才會穩定生效。

Activity 程式碼

package lab.sodino.menutest;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

/**
 * @author Sodino E-mail: sodinoopen@hotmail.com
 * @version Time:2011-1-26 下午04:42:04
 */
public class MenuAct extends Activity {

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

    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = new MenuInflater(getApplicationContext());
        inflater.inflate(R.menu.menu, menu);
        setMenuBackground();
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        String info = "";
        switch (item.getItemId()) {
            case R.id.menu_add:    info = "Add";    break;
            case R.id.menu_delete: info = "Delete"; break;
            case R.id.menu_home:   info = "Home";   break;
            case R.id.menu_help:   info = "Help";   break;
            default:               info = "NULL";   break;
        }
        Toast toast = Toast.makeText(this, info, Toast.LENGTH_SHORT);
        toast.show();
        return super.onOptionsItemSelected(item);
    }

    // 關鍵:重寫 LayoutFactory.onCreateView() 以自訂版面
    protected void setMenuBackground() {
        MenuAct.this.getLayoutInflater().setFactory(new android.view.LayoutInflater.Factory() {

            /**
             * name    - Tag name to be inflated.
             * context - The context the view is being created in.
             * attrs   - Inflation attributes as specified in XML file.
             */
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                // 只攔截系統選單項目
                if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
                    try {
                        LayoutInflater f = getLayoutInflater();
                        final View view = f.createView(name, null, attrs);

                        new Handler().post(new Runnable() {
                            public void run() {
                                // 設定背景圖片
                                view.setBackgroundResource(R.drawable.menu_background);
                            }
                        });
                        return view;
                    } catch (InflateException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                return null;   // 其他一律交回系統預設處理
            }
        });
    }
}

選單資源 /res/menu/menu.xml

<?XML version="1.0" encoding="utf-8"?>
<menu XMLns:android="https://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_add"    android:title="Add"    android:icon="@drawable/menu_add"></item>
    <item android:id="@+id/menu_delete" android:title="Delete" android:icon="@drawable/menu_delete"></item>
    <item android:id="@+id/menu_home"   android:title="Home"   android:icon="@drawable/menu_home"></item>
    <item android:id="@+id/menu_help"   android:title="Help"   android:icon="@drawable/menu_help"></item>
</menu>

兩個務實的提醒

Factory 的 onCreateView() 一定要對非目標名稱回傳 null,否則會把整個版面的膨脹流程弄壞。另外,這裡直接引用了 com.android.internal 底下的類別名稱,屬於非公開實作,Android 版本升級後名稱或行為都可能改變;若要在正式產品中使用,建議加上 try-catch 保護並準備退回預設樣式的方案。

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