Android适配 - 实现4.0以后的导航栏菜单键

虚拟导航栏常见有三个按钮:分别是Back键,Home键,Recent键。Android 4.0以后默认不显示Menu键,在API 22以上系统源码对Menu键的显示也有修改。本篇将开启Menu键并且适配Android 4.0 - Android 7.0

QQ一直沿用Menu键

纵观目前很多应用都未采用Menu键,QQ却一直沿用,并且利用Menu键显示一些快捷菜单,例如:版本更新、意见反馈、退出登录。京东也利用Menu键做一些快捷菜单。

QQ Menu键 京东 Menu键

利用反射开启Menu键

分析PhoneWindow源码后,利用反射可以强行显示Memu键,由于API 22以后此部分的系统代码略有改动,在此进行适配。完整代码如下:

    /**
     * 显示虚拟导航栏菜单按钮.
     * 虚拟导航栏菜单按钮在4.0以后默认不显示,可以利用反射强行设置,调用位置须在setContentView之后
     * 具体可以参考5.0以及6.0中的PhoneWindow类源码
     *
     * @param window {@link Window}
     */
    public static void showNavigationMenuKey(Window window) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            showNavigationLollipopMR1(window);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            showNavigationIceCreamSandwich(window);
        }
    }

    /**
     * 显示虚拟导航栏菜单按钮.
     * Android 4.0 - Android 5.0
     * API 14 - 21
     *
     * @param window {@link Window}
     */
    private static void showNavigationIceCreamSandwich(Window window) {
        try {
            int flags = WindowManager.LayoutParams.class.getField("FLAG_NEEDS_MENU_KEY").getInt(null);
            window.addFlags(flags);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示虚拟导航栏菜单按钮.
     * Android 5.1.1 - Android 7.0,Android 8.0 未测试
     * API 22 - 25
     *
     * @param window {@link Window}
     */
    private static void showNavigationLollipopMR1(Window window) {
        try {
            Method setNeedsMenuKey = Window.class.getDeclaredMethod("setNeedsMenuKey", int.class);
            setNeedsMenuKey.setAccessible(true);
            int value = WindowManager.LayoutParams.class.getField("NEEDS_MENU_SET_TRUE").getInt(null);
            setNeedsMenuKey.invoke(window, value);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

效果如图

测试手机为:Nexus 6,系统分别5.0(API 21)、6.0(API 23)、7.1.1(API 25)

源码分析

1.首先有视图的地方就会有Window,常用的Activity也对应这一个Window。我们在Activity的onCreate方法中设置布局。

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

进入setContentView方法中,我们可以看到它和Window关联在一起了

    /**
     * Set the activity content from a layout resource.  The resource will be
     * inflated, adding all top-level views to the activity.
     *
     * @param layoutResID Resource ID to be inflated.
     *
     * @see #setContentView(android.view.View)
     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
     */
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

2.在setContentView过程中,Activity会将具体实现交给Window,Window是一个抽象类,它的唯一实现类是PhoneWindow,那么直接分析它的具体逻辑。

在PhoneWindow的setContentView法中会初始化DecorView,如果没有DecorView则创建它。

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
            installDecor();//从调用此方法继续分析
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            view.setLayoutParams(params);
            final Scene newScene = new Scene(mContentParent, view);
            transitionTo(newScene);
        } else {
            mContentParent.addView(view, params);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

3.创建好DecorView后,继续按照设定的主题样式形成最终的DecorView。

    private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            mDecor = generateDecor(-1);
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor);//设置主题样式
            ......//省略后续代码
        }

4.在关键的generateLayout方法中,即可找到Menu键的相关调用。

protected ViewGroup generateLayout(DecorView decor) {
    //......省略代码段
    final Context context = getContext();
    final int targetSdk = context.getApplicationInfo().targetSdkVersion;
    final boolean targetPreHoneycomb = targetSdk<android.os.Build.VERSION_CODES.HONEYCOMB;
    final boolean targetPreIcs = targetSdk<android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
    final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.LOLLIPOP;
    final boolean targetHcNeedsOptions = context.getResources().getBoolean(
                R.bool.target_honeycomb_needs_options_menu);
    final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);
    //Menu的显示或者隐藏
    if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
        setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE);
    } else {
        setNeedsMenuKey(WindowManager.LayoutParams.NEEDS_MENU_SET_FALSE);
    }
    //...省略代码段
}

5.上述分析的系统源码基于API 26,在API 21中,此部分略有不同,如下:

protected ViewGroup generateLayout(DecorView decor) {
    //......省略代码段
    final Context context = getContext();
    final int targetSdk = context.getApplicationInfo().targetSdkVersion;
    final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB;
    final boolean targetPreIcs = targetSdk<android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
    final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.LOLLIPOP;
    final boolean targetHcNeedsOptions = context.getResources().getBoolean(
                R.bool.target_honeycomb_needs_options_menu);
    final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE);

    if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) {
        addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY);
    } else {
        clearFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY);
    }
    //...省略代码段
}

因此利用反射即可完成显示Menu键,注意调用方法时需要在setContentView之后,也就是在系统完成DecorView之后调用,强行显示。Menu的点击事件只需要监听onKeyDown,判断keyCode即可。

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//注意调用顺序
        ScreenUtil.showNavigationMenuKey(getWindow());
        initView();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            Toast.makeText(this, "menu click", Toast.LENGTH_LONG).show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


本文参考:Android 4.0以上设备的虚拟按键中menu键的显示问题

猜你喜欢

转载自blog.csdn.net/scau_zhangpeng/article/details/78955886