I'm developing some Android application, and I've got some code for menu:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:showAsAction="ifRoom"
android:id="@+id/menuItemToLeft"
android:icon="@drawable/to_left" />
<item
android:showAsAction="ifRoom"
android:id="@+id/menuItemToRight"
android:icon="@drawable/to_right"/>
</menu>
I use "showAsAction" in order to show this items on Action Bar. Also I've got 3 tabs for navigation. But there is the following task: remove (or set visibility as false) this items from Action bar when tab with 0 positions is selected. But I don't understand how I can do it:
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition()==0) {
//some code
}
}
Get a MenuItem pointing to such item, call setVisible on it to adjust its visibility and then call invalidateOptionsMenu() on your activity so the ActionBar menu is adjusted accordingly. Save this answer.
How do we hide the menu on toolbar in one fragment? When you click the show button to open a fragment, you can see the fragment menu items ordered before activity menu items. This is because of the menu item's android:orderInCategory attribute value. When you click the hide button to hide the fragment.
onCreateOptionsMenu() is called by the Android runtime when it need to create the option menu.
you can access the MenuItem with the id menuItemPinQuote like this in your Android/Java code: public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) { menuInflater. inflate(R. menu.
Try just not show them using:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
menu.findItem(R.id.menuItemToLeft).setVisible(true);
menu.findItem(R.id.menuItemToRight).setVisible(false);
return true;
}
//true or false depending on your requirements
or to delete:
menu.removeItem(x); //where x is the number of the menu item from 0,1,...
You may then need to create the MenuItem again using menu.Add()
A very small solution for this :
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Menu myMenu;
protected void onCreate(Bundle savedInstanceState) {
.....
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
myMenu = menu;
return true;
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.feedsenglish)
{
myMenu.findItem(R.id.allfeeds).setVisible(false);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With