Reputation: 35
I've created an item - activity2
in menu(in res>menu>main.xml
) and I want when the user will click the activity2
, activity1
will hide (which is already running) and activity2
will show.
And also when user press back the activity2
will hide and activity1
will visible to the user.
How to do this? Please explain.
Upvotes: 0
Views: 1417
Reputation: 2737
You can get onclick event of menu item in onOptionsItemSelected
.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.activity2:
// start your activity2
startActivity(new Intent(MainActivity.this, Activity2.class));
// no need to finish MainActivity
default:
return super.onOptionsItemSelected(item);
}
}
MainActivity
is not destroyed so if u press back on Activity2
then MainActivity
will be displayed.Upvotes: 1
Reputation: 785
You need to use onPrepareOptionMenu method in your Activity where in you can set visibility using setVisible. you can refer below code as an example:
public boolean onPrepareOptionsMenu(Menu menu)
{
MenuItem register = menu.findItem(R.id.menuregistrar);
if(userRegistered)
{
register.setVisible(false);
}
else
{
register.setVisible(true);
}
return true;
}
Upvotes: 0
Reputation: 22945
You should use menuItem.setVisible(false);
to hide menuItem tha maintain its visibility,
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem menuItem = menu.findItem(R.id.icon_websearch);//your icon
menuItem.setVisible(false);
return super.onPrepareOptionsMenu(menu);
}
Upvotes: 0