Example:
When click on Menu3, I want Menu1 and Menu2 to be displayed.
@Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem Menu1 = menu.findItem(R.id.Menu1);
MenuItem Menu2 = menu.findItem(R.id.Menu2);
Menu1.setVisible(false);
Menu2.setVisible(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Menu3) {
item.setVisible(false);
Menu menu;
menu.findItem(R.id.Menu1).setVisible(true);
return true;
}
return super.onOptionsItemSelected(item);
}
The following code is not working:
Menu menu;
menu.findItem(R.id.Menu1).setVisible(true);
This code:
Menu menu;
menu.findItem(R.id.Menu1).setVisible(true);
Will not work as the menu
varaible is not initialized. You should initialize the menu
variable as needed and then call to setVisible method.
You can use some boolean
variables to set the desired state for the menu items. Then as soon as the user clicks on the Menu3 item, you change the boolean
values and call invalidateOptionsMenu();
. This will cause the menu to be recreated and so the other menu items will be shown as desired:
public class MainActivity extends AppCompatActivity
{
private boolean showMenu1, showMenu2;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set the initial state here:
showMenu1 = false;
showMenu2 = false;
...
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.findItem(R.id.Menu1).setVisible(showMenu1);
menu.findItem(R.id.Menu2).setVisible(showMenu2);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.Menu3)
{
showMenu1 = true;
showMenu2 = true;
invalidateOptionsMenu();
return true;
}
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.