在我的活动中,我在操作栏中有三个图标(搜索 - 添加 - 计数),我想在变量hideIcon
为true
时隐藏这些图标。
以下是我的代码。
MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
case R.id.action_add_tip:
return true;
case R.id.action_count_tip:
return true;
case android.R.id.home:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
menu.activity_main_actions.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- Search -->
<item android:id="@+id/action_search"
android:icon="@drawable/header_search"
android:title="@string/action_search"
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"/>
<!-- Add Tip -->
<item android:id="@+id/action_add_tip"
android:icon="@drawable/header_add"
android:title="@string/action_add_tip"
android:showAsAction="ifRoom" />
<!-- Count Tips -->
<item android:id="@+id/action_count_tip"
android:icon="@drawable/header_count"
android:title="@string/action_count_tip"
android:showAsAction="ifRoom" />
</menu>
如何隐藏if(hideIcon)
true
?
提前谢谢。
答案 0 :(得分:3)
//anywhere in your code
hideIcon = HIDE_MENU; // setting state
invalidateOptionsMenu(); // now onCreateOptionsMenu(...) is called again
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// inflate menu from xml
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.settings, menu);
if (hideIcon)
{
for (int i = 0; i < menu.size(); i++)
menu.getItem(i).setVisible(false);
}
}