昨天做actionbar相关的东西,突然发现死活不在actionbar的右边显示选项Item,今天终于解决了,先把出现问题时的情况说明一下。
module的build.gradle如下:
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "com.xxxx" minSdkVersion 14 targetSdkVersion 23 versionCode 1 versionName "1.0" /* ndk{ moduleName "GeiHuiNDK" ldLibs "log" ,"m","z" abiFilters "armeabi","armeabi-v7a" , "x86" }*/ } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } useLibrary 'org.apache.http.legacy' //android SDK 6.0以后取消了HttpClient相关jar包,如果需要使用需要添加这行代码 } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.0.1' compile files('libs/xUtils-2.6.14.jar') compile 'com.android.support:design:23.0.1' compile 'com.umeng.analytics:analytics:latest.integration' }
项目中所有的Activity都继承自android.support.v4.app.FragmentActivity;
在具体的Acitivity中重写ActionBar相关的两个方法:
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_regist, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.item1: onBackPressed(); return true; default: return true; } }menu_regist代码如下:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/item1" android:title="@string/LoginTitle" app:showAsAction="always"/> </menu>
运行项目页面效果如下图:
按物理menu键出现item,效果如下:
这不是我要的效果啊亲,网上搜怎么办,找了好久,找到了一个强制在右边显示Item的方法,拿来试一下,看看效果如何。方法是在activity的oncreate方法里添加如下代码:
try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if(menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { LogUtils.e("error",ex.getMessage()); }运行一下看看效果呗,变成这样了:
居然在右边出现了三个点,这不是浮动窗口的按钮吗,还不是我要的效果。咋弄啊,继续搜索,记得有人说需要把menu.xml文件中itme标签的android:showAsAction属性改为app:showAsAction ,然后就在menu标签中加入 xmlns:app="http://schemas.android.com/apk/res-auto",看看我的也是这样写的啊,要不我该回去试验一下吧,于是删除xmlns:app="http://schemas.android.com/apk/res-auto",把app:showAsAction改为android:showAsAction,发现AS提示这个属性错误,红线出现,他妈的是不是不能这么改啊。结果证明我被AS欺骗了,忽略这个错误提示,Ctrl+F9直接编译,通过,那就运行一下吧,靠起来了,看到我要的效果了,满脸泪奔啊,亲啊 ,我被你傻傻的欺骗了。
效果如下: