我在Galaxy S3上遇到了一个问题,即在操作栏溢出菜单中应显示的操作不在那里。因此,用户体验有些混乱 - 在Galaxy S3上,我的操作栏只显示应用程序标志和名称,但没有提供额外的功能。
我希望在所有运行Android 4.x的设备上拥有相同的用户体验,并在溢出菜单中显示操作。是否可以在不使用像ActionBarSherlock这样的第三方组件的情况下实现这一点?
谢谢
我在Galaxy S3上遇到了一个问题,即在操作栏溢出菜单中应显示的操作不在那里。因此,用户体验有些混乱 - 在Galaxy S3上,我的操作栏只显示应用程序标志和名称,但没有提供额外的功能。
我希望在所有运行Android 4.x的设备上拥有相同的用户体验,并在溢出菜单中显示操作。是否可以在不使用像ActionBarSherlock这样的第三方组件的情况下实现这一点?
谢谢
有一种快速而简单的方法,可以使用反射来设置应用程序的ViewConfiguration
实例中的字段,从而伪造硬件菜单按钮的缺失。
以下代码片段可以添加到您的活动中,并在onCreate()
期间调用。
private void enableActionBarOverflow() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class
.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
这不是一个完美的解决方案,因为ViewConfiguration的实现可能在未来的某个时候发生改变,并且由于sHasPermanentMenuKey字段是私有的,所以不能保证该字段始终存在。
然而,如果您绝对必须在具有菜单键的设备上使用溢出菜单,则只能将其作为最后的手段使用。
假设您的最低API为11(蜂窝)或更高版本,则更好的解决方案是自己制作溢出菜单,如下所示:
Add a menu item for the overflow in your menu.xml, setting it to always show and inflate in your onCreateOptionsMenu()
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
...
<item
android:id="@+id/action_overflow"
android:icon="@drawable/ic_action_settings"
android:title="@string/settings"
android:showAsAction="always">
</item>
</menu>
,
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
Create a separate overflow_menu.xml resource for your choices you want in the overflow menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/overflow_action1"
android:title="@string/overflow_action1">
</item>
<item
android:id="@+id/overflow_action2"
android:title="@string/overflow_action2">
</item>
</menu>
In your onOptionsItemSelected()
method, handle the selection of your overflow menu
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case R.id.action_overflow:
PopupMenu popup = new PopupMenu(
this, findViewById(R.id.action_overflow));
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.overflow_menu, popup.getMenu());
popup.setOnMenuItemClickListener(this);
popup.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Implement the PopupMenu.OnMenuItemClickListener
interface in your activity to handle the clicks of the overflow items
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.overflow_action1:
//do stuff
return true;
case R.id.overflow_action2:
//do stuff
return true;
default:
return false;
}
}