我正在尝试在设计视图中的Android操作栏上添加菜单图标,我可以在正确的位置看到菜单,但是当我尝试预览时,将其设置为app:showAsAction="always"
时,菜单未显示为隐藏的下拉菜单。谁能帮我解决此问题?
设计视图
APP运行预览
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<item
android:id="@+id/action_home"
android:orderInCategory="0"
android:icon="@drawable/outline_home_white_48"
app:showAsAction="always"
android:title="Home">
</item>
<item
android:id="@+id/action_option"
android:icon="@drawable/menu_icon"
android:title="Options"
app:showAsAction="always">
<menu>
<item
android:id="@+id/action_settings"
android:title="@string/action_settings">
</item>
<item
android:id="@+id/action_update"
android:title="@string/update_app">
</item>
</menu>
</item>
</menu>
我的Java代码
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.action_home:
fragment = new HomeFragment();
break;
default:
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
}
return super.onOptionsItemSelected(item);
}
Android构建版本
android {
compileSdkVersion 28
buildToolsVersion '28.0.3'
defaultConfig {
applicationId "com.myapp.aaa"
minSdkVersion 22
targetSdkVersion 28
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
答案 0 :(得分:2)
尝试使用android:showAsAction
而不是app:showAsAction
。
同时添加tools:ignore="AppCompatResource"
我已经解决了这里的完整代码
<item
android:id="@+id/action_home"
android:orderInCategory="0"
android:icon="@drawable/outline_home_white_48"
android:showAsAction="always"
android:title="Home"
tools:ignore="AppCompatResource">
</item>
<item
android:id="@+id/action_search"
android:orderInCategory="0"
android:icon="@drawable/search_icon_white"
android:showAsAction="always|collapseActionView"
app:actionViewClass="android.widget.SearchView"
android:title="Search Branch"
tools:ignore="AppCompatResource">
</item>
<item
android:id="@+id/action_option"
android:icon="@drawable/menu_icon"
android:title="Options"
android:showAsAction="always"
tools:ignore="AppCompatResource">
<menu>
<item
android:id="@+id/action_settings"
android:title="@string/action_settings">
</item>
<item
android:id="@+id/action_update"
android:title="@string/update_app">
</item>
</menu>
</item>