标签:actionbar android2.x shaspermanentmenukey
好久没有在csdn上写博客了,最近闲来无事,决定仿微信界面做几个东西,原本以为挺简单的事情,结果折腾了好久才把第一步的ActionBar搞定,其中过程可谓坎坷之极,记录下来,以便给各位分享。
首先介绍一下我的手机,我的手机是android2.3.4的系统,要使用ActionBar,有两种选择,一个是使用大名鼎鼎的开源组件:ActionBarSherlock;一个是使用google自己出的android-support-v7包;ActionBarSherlock自从google推出android-support-v7包以后,基本上要退出历史舞台了,因此我决定使用android-support-v7一试。
首先下载android-support-v7-appcompat(包括jar包和资源项目),新建项目weixin(注意最低sdk版本要求),引入android-support-v7-appcompat.jar(把该jar包放到lib目录下,刷新工程),并把android-support-v7-appcompat资源项目作为类库引入到项目中,项目结果如下
新建MainActivity,继承类android.support.v7.app.ActionBarActivity,代码如下:
package com.example.weixin; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; public class MainActivity extends ActionBarActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }修改res\values\styles.xml,使用androi-support-v7的Theme.AppCompat.Light.DarkActionBar风格,如下
<resources> <!-- Base application theme, dependent on API level. This theme is replaced by AppBaseTheme from res/values-vXX/styles.xml on newer devices. --> <style name="AppBaseTheme" parent="Theme.AppCompat.Light.DarkActionBar"</span>> <!-- Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. --> </style> <!-- Application theme. --> <style name="AppTheme" parent="AppBaseTheme"> <!-- All customizations that are NOT specific to a particular API-level can go here. --> </style> </resources>修改res\menu\main.xml,如下:
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:alpha="http://schemas.android.com/apk/res-auto"> <!--android.widget.SearchView在api11之前不存在,需要使用 android.support.v7.widget.SearchView--> <item android:id="@+id/action_search" alpha:actionViewClass="android.support.v7.widget.SearchView" android:actionProviderClass="" android:icon="@drawable/actionbar_search_icon" alpha:showAsAction="ifRoom|collapseActionView" android:title="@string/action_search"/> <item android:id="@+id/action_groupchat" android:icon="@drawable/ofm_group_chat_icon" alpha:showAsAction="never" android:title="@string/action_groupchat"/> <item android:id="@+id/action_addfriend" android:icon="@drawable/ofm_add_icon" alpha:showAsAction="never" android:title="@string/action_addfriend"/> <item android:id="@+id/action_scanqrcode" android:icon="@drawable/ofm_qrcode_icon" alpha:showAsAction="never" android:title="@string/action_scanqrcode"/> <item android:id="@+id/action_feedback" android:icon="@drawable/ofm_feedback_icon" alpha:showAsAction="never" android:title="@string/action_feedback"/> </menu>
经过这样设置以后,按理来说就应该可以了,我们在android2.3环境下运行试试
android2.3运行效果:
发现ActionBar没有overflow按钮,点击物理menu键在下面出现了上下文菜单,这并不是我们想要的效果,查看android doc可知,overflow按钮的显示情况和手机的硬件情况是有关系的,如果手机没有物理Menu键的话,overflow按钮就可以显示, 如果有物理Menu键的话,overflow按钮就不会显示出来,要改变这个默认行为,在ViewConfiguration这个类中, 有一个叫做sHasPermanentMenuKey的静态变量,系统就是根据这个变量的值来判断手机有没有物理Menu键的。当然这是一个内部变量,我们无法直接访问它,但是可以通过反射的方式修改它的值,让它永远为false就可以了。在MainActivity中增加方法
private void setOverflowShowingAlway(){ try{ ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class .getDeclaredField("sHasPermanentMenuKey"); menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); }catch(Exception e){ e.printStackTrace(); } }并在onCreate(Bundle savedInstanceState)方法中调用
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setOverflowShowingAlway(); }
private void setOptionalIconsVisible(Menu menu){ if(menu == null) return; if(!menu.getClass().getSimpleName().equals("MenuBuilder")) return; try { Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE); m.setAccessible(true); m.invoke(menu, true); } catch (Exception e) { } } @Override public boolean onMenuOpened(int featureId, Menu menu) { if(featureId == Window.FEATURE_ACTION_BAR){ setOptionalIconsVisible(menu); } return super.onMenuOpened(featureId, menu); }
重新运行,发现android4.0环境下已经运行正常了,运行效果如下:
正在高兴之余,打开android2.3环境下运行,发现android2.3环境并没有任何变化,overflow按钮没有出来,且按下物理menu键以后再下面出现了上下文菜单,在logcat中出现以下错误:
03-06 13:57:51.587: W/System.err(328): java.lang.NoSuchFieldException: sHasPermanentMenuKey 03-06 13:57:51.606: W/System.err(328): at java.lang.ClassCache.findFieldByName(ClassCache.java:446) 03-06 13:57:51.616: W/System.err(328): at java.lang.Class.getDeclaredField(Class.java:666) 03-06 13:57:51.626: W/System.err(328): at com.example.weixin.MainActivity.setOverflowShowingAlway(MainActivity.java:32) 03-06 13:57:51.636: W/System.err(328): at com.example.weixin.MainActivity.onCreate(MainActivity.java:19) 03-06 13:57:51.636: W/System.err(328): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 03-06 13:57:51.647: W/System.err(328): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586) 03-06 13:57:51.656: W/System.err(328): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638) 03-06 13:57:51.656: W/System.err(328): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 03-06 13:57:51.667: W/System.err(328): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928) 03-06 13:57:51.676: W/System.err(328): at android.os.Handler.dispatchMessage(Handler.java:99) 03-06 13:57:51.696: W/System.err(328): at android.os.Looper.loop(Looper.java:123) 03-06 13:57:51.707: W/System.err(328): at android.app.ActivityThread.main(ActivityThread.java:3647) 03-06 13:57:51.717: W/System.err(328): at java.lang.reflect.Method.invokeNative(Native Method) 03-06 13:57:51.736: W/System.err(328): at java.lang.reflect.Method.invoke(Method.java:507) 03-06 13:57:51.746: W/System.err(328): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-06 13:57:51.756: W/System.err(328): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-06 13:57:51.756: W/System.err(328): at dalvik.system.NativeStart.main(Native Method)
首先查找android4.0版本中看看在哪使用了ViewConfiguration.hasPermanentMenuKey()方法,经过分析是在类com.android.internal.view.ActionBarPolicy中的showsOverflowMenuButton()使用了,代码如下:
public boolean showsOverflowMenuButton() { return !ViewConfiguration.get(mContext).hasPermanentMenuKey(); }
@Override public void initForMenu(Context context, MenuBuilder menu) { super.initForMenu(context, menu); final Resources res = context.getResources(); final ActionBarPolicy abp = ActionBarPolicy.get(context); if (!mReserveOverflowSet) { mReserveOverflow = abp.showsOverflowMenuButton(); } if (!mWidthLimitSet) { mWidthLimit = abp.getEmbeddedMenuWidthLimit(); } // Measure for initial configuration if (!mMaxItemsSet) { mMaxItems = abp.getMaxActionButtons(); } int width = mWidthLimit; if (mReserveOverflow) { if (mOverflowButton == null) { // 创建overflow按钮 mOverflowButton = new OverflowMenuButton(mSystemContext); final int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); mOverflowButton.measure(spec, spec); } width -= mOverflowButton.getMeasuredWidth(); } else { mOverflowButton = null; } mActionItemWidthLimit = width; mMinCellSize = (int) (ActionMenuView.MIN_CELL_SIZE * res.getDisplayMetrics().density); // Drop a scrap view as it may no longer reflect the proper context/config. mScrapActionButtonView = null; }原来在ActionBarMenu初始化时,是根据showsOverflowMenuButton()的返回结果来决定是否创建overflow按钮的,而在android-support-v7-appcompat中也有类ActionBarPolicy和ActionMenuPresenter,其中类ActionMenuPresenter的initForMenu方法与android4.0版本代码差不多,但是类ActionBarPolicy的showsOverflowMenuButton()代码却如下:
public boolean showsOverflowMenuButton() { return Build.VERSION.SDK_INT >= 11; }判断sdk的版本大于11(版本大于android3.0)即返回true,否则返回false。看来通过反射方法修改类ActionBarPolicy的showsOverflowMenuButton()返回值是不太可能了,继续往下分析,查看一下类ActionMenuPresenter的initForMenu方法在哪被调用了,结果分析,原来是在类android.support.v7.internal.widget.ActionBarView的configPresenters(MenuBuilder builder)方法中调用的,而configPresenters方法又是在setMenu(SupportMenu menu, MenuPresenter.Callback cb)中调用的,源代码如下:
public void setMenu(Menu menu, MenuPresenter.Callback cb) { if (menu == mOptionsMenu) return; if (mOptionsMenu != null) { mOptionsMenu.removeMenuPresenter(mActionMenuPresenter); mOptionsMenu.removeMenuPresenter(mExpandedMenuPresenter); } MenuBuilder builder = (MenuBuilder) menu; mOptionsMenu = builder; if (mMenuView != null) { final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); if (oldParent != null) { oldParent.removeView(mMenuView); } } if (mActionMenuPresenter == null) { mActionMenuPresenter = new ActionMenuPresenter(mContext); mActionMenuPresenter.setCallback(cb); mActionMenuPresenter.setId(com.android.internal.R.id.action_menu_presenter); mExpandedMenuPresenter = new ExpandedActionViewMenuPresenter(); } ActionMenuView menuView; final LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (!mSplitActionBar) { mActionMenuPresenter.setExpandedActionViewsExclusive( getResources().getBoolean( com.android.internal.R.bool.action_bar_expanded_action_views_exclusive)); configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); final ViewGroup oldParent = (ViewGroup) menuView.getParent(); if (oldParent != null && oldParent != this) { oldParent.removeView(menuView); } addView(menuView, layoutParams); } else { mActionMenuPresenter.setExpandedActionViewsExclusive(false); // Allow full screen width in split mode. mActionMenuPresenter.setWidthLimit( getContext().getResources().getDisplayMetrics().widthPixels, true); // No limit to the item count; use whatever will fit. mActionMenuPresenter.setItemLimit(Integer.MAX_VALUE); // Span the whole width layoutParams.width = LayoutParams.MATCH_PARENT; configPresenters(builder); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); if (mSplitView != null) { final ViewGroup oldParent = (ViewGroup) menuView.getParent(); if (oldParent != null && oldParent != mSplitView) { oldParent.removeView(menuView); } menuView.setVisibility(getAnimatedVisibility()); mSplitView.addView(menuView, layoutParams); } else { // We'll add this later if we missed it this time. menuView.setLayoutParams(layoutParams); } } mMenuView = menuView; } private void configPresenters(MenuBuilder builder) { if (builder != null) { builder.addMenuPresenter(mActionMenuPresenter); builder.addMenuPresenter(mExpandedMenuPresenter); } else { mActionMenuPresenter.initForMenu(mContext, null); mExpandedMenuPresenter.initForMenu(mContext, null); mActionMenuPresenter.updateMenuView(true); mExpandedMenuPresenter.updateMenuView(true); } }
看红字加粗部分,这是实例化ActionMenuPresenter方法的过程,原来如此!我们只要把ActionBarView中修改mActionMenuPresenter的值即可,废话少说,修改MainActivity的setOverflowShowingAlway()方法如下:
private void setOverflowShowingAlway(){ try{ if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){ // android3.0以后的版本才存在sHasPermanentMenuKey属性 ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class .getDeclaredField("sHasPermanentMenuKey"); menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } else { // 获取actionBarView final ActionBarView actionBarView = (ActionBarView) findViewById(android.support.v7.appcompat.R.id.action_bar); MenuPresenter.Callback menuCallback = new MenuPresenter.Callback() { @Override public boolean onOpenSubMenu(MenuBuilder subMenu) { android.view.Window.Callback cb = getWindow().getCallback(); if (cb != null) { cb.onMenuOpened(Window.FEATURE_ACTION_BAR, subMenu); return true; } return false; } @Override public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { closeOptionsMenu(); } }; Field menuPresenterField = actionBarView.getClass().getSuperclass().getDeclaredField("mActionMenuPresenter"); menuPresenterField.setAccessible(true); final ActionMenuPresenter menuPresenter = new ActionMenuPresenter(this); menuPresenter.setReserveOverflow(true); // 这句是关键,设置overflow可见 menuPresenter.setCallback(menuCallback); menuPresenter.setId(android.support.v7.appcompat.R.id.action_menu_presenter); // 修改actionBarView.mActionMenuPresenter=menuPresenter; menuPresenterField.set(actionBarView, menuPresenter); Field expandedMenuPresenterField = actionBarView.getClass().getDeclaredField("mExpandedMenuPresenter"); expandedMenuPresenterField.setAccessible(true); Constructor contructor = Class.forName("android.support.v7.internal.widget.ActionBarView$ExpandedActionViewMenuPresenter").getDeclaredConstructor(actionBarView.getClass()); contructor.setAccessible(true); Object expandedMenuPresenter = contructor.newInstance(actionBarView); // 修改actionBarView.mExpandedMenuPresenter=expandedMenuPresenter; expandedMenuPresenterField.set(actionBarView, expandedMenuPresenter); } } catch(Exception e){ e.printStackTrace(); } }
以上代码首先判断sdk版本是否是android3.0之后的版本,如果是则直接反射修改ViewConfiguration的sHasPermanentMenuKey的值;否则查找出ActionBarView,替换该对象的mActionMenuPresenter及mExpandedMenuPresenter的值,其中mActionMenuPresenter需要设置setReserveOverflow(true),也就是ActionMenuPresenter的mReserveOverflow=true,mReserveOverflowSet=true,这样就能保证程序在运行到ActionMenuPresenter的initForMenu方法时,不z再获取ActionBarPolicy的showsOverflowMenuButton()的返回值作为判断是否增加overflow按钮的依据。
重新运行,呵呵,overflow按钮可以出来了,点击overflow按钮也出现了下来菜单,但是菜单只有文字没有显示图标,并且按物理menu键菜单还是显示在下边。经过分析,原来是android3.0之前的类com.android.internal.policy.impl.PhoneWindow并没有任何ActionBar的代码,而在android3.0以后的版本中增加了不少ActionBar代码,修改MainActivity的onMenuOpened(int featureId, Menu menu)方法如下:
@Override public boolean onMenuOpened(int featureId, Menu menu) { if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){ // android3.0以后的版本,参数menu不为空,直接通过反射方法修改setOptionalIconsVisible的值 if(featureId == Window.FEATURE_ACTION_BAR){ setOptionalIconsVisible(menu); } return super.onMenuOpened(featureId, menu); } else { ActionBarView actionBarView = (ActionBarView) findViewById(android.support.v7.appcompat.R.id.action_bar); // 通过点击overflowButton时,传入的参数featureId为FEATURE_ACTION_BAR,而通过点击menu按键,传入的参数featureId为FEATURE_OPTIONS_PANEL if(featureId == Window.FEATURE_ACTION_BAR){ // android3.0之前的版本,由于phonewindow的机制,导致传进的menu是空的,需要把menu赋值为ActionMenuPresenter.mMenu if(menu == null){ try{ Field menuPresenterField = actionBarView.getClass().getSuperclass().getDeclaredField("mActionMenuPresenter"); menuPresenterField.setAccessible(true); ActionMenuPresenter menuPresenter = (ActionMenuPresenter) menuPresenterField.get(actionBarView); Field menuField = BaseMenuPresenter.class.getDeclaredField("mMenu"); menuField.setAccessible(true); menu = (Menu) menuField.get(menuPresenter); } catch(Exception e){ e.printStackTrace(); } } setOptionalIconsVisible(menu); return super.onMenuOpened(featureId, menu); } else { actionBarView.showOverflowMenu(); // 把下拉菜单显示到ActionBar上 return false; } } }
以上代码首先判断首先判断sdk版本是否是android3.0之后的版本,如果是则直接反射修改menu的setOptionalIconsVisible;否则根据传入的参数featureId是否等于Window.FEATURE_ACTION_BAR来判断用户是通过点击overflow按钮还是点击物理menu键触发的,如果是通过overflow按钮触发的,则其featureId为Window.FEATURE_ACTION_BAR,但是menu=null,后面根据发射方法对menu进行赋值,并修改menu的setOptionalIconsVisible=true;如果是通过点击物理menu键触发的,则其featureId为Window.FEATURE_OPTIONS_PANEL,则调用ActionBarView的showOverflowMenu()方法,把菜单挂接到overflow下。
至此所有修改已完成,我们看一下在android2.3环境下运行效果:
标签:actionbar android2.x shaspermanentmenukey
原文地址:http://blog.csdn.net/job_hesc/article/details/44103875