This question already has an answer here:
How can i change Menu Item icon programmatically?
(1 answer)
Closed 7 months ago.
I want to clarify that I talk about a navigation drawer menu and not an action button icon.
I need to change an menu icon programmatically. For this I done next:
private Menu menu;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
getMenuInflater().inflate(R.menu.navigation_menu, menu);
return super.onCreateOptionsMenu(menu);
}
.... and I try to change icon item with :
menu.getItem(6).setIcon(getResources().getDrawable(R.mipmap.ic_flash_on_black_24dp));
Unfortunately the item remain unchanged. Can help me to solve problem please?
I have observed that getDrawable is deprecated but no ideea how to use the new one.
The answer was very simple:
private Menu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
menu = navigationView.getMenu();
...
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_light) {
if (canTorch) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
menu.getItem(6).setIcon(getResources().getDrawable(R.mipmap.ic_flash_on_black_24dp));
} else {
turnOnFlashLight();
isTorchOn = true;
menu.getItem(6).setIcon(getResources().getDrawable(R.mipmap.ic_flash_off_black_24dp));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
All was about : menu = navigationView.getMenu();
Try to place icon modification code in onPrepareOptionsMenu method:
Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
Related
This question already has answers here:
Android Toolbar Adding Menu Items for different fragments
(12 answers)
Closed 4 years ago.
I want to add Filter option in Tool Bar which can be used in multiple fragments by each fragment has a different filter. For example, if I click A fragment a toolbar appears with filter option having today date, and if I click B fragment a toolbar appears with filter option having this start month date.
I am getting Icon in each and every Fragment but How to use click event in the fragment
private void setupToolBar() {
drawerLayout = findViewById(R.id.drawer_layout);
initNavigationDrawer();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_filter:
Toast.makeText(this,"Main activity",Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
Try Like this
//Here i am doing by using string you can check current Fragment so it will change according to Fragment
public class YourActivity extends Activity {
private Menu menu;
private String DateTitle = "Date'";
private String MonthTitle = "Month";
private boolean inBed = false;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Create your menu...
this.menu = menu;
return true;
}
private void updateMenuTitles() {
MenuItem bedMenuItem = menu.findItem(R.id.action_filter);
>//Here i am doing by using string you can check current Fragment so it will change according to Fragment
if (inBed) {
bedMenuItem.setTitle(MonthTitle);
} else {
bedMenuItem.setTitle(DateTitle);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_filter:
if(item.getTitle().toString() == "Date"){
Toast.makeText(this,"Date",Toast.LENGTH_LONG).show();
}
if(item.getTitle().toString() == "Month")
Toast.makeText(this,"Month",Toast.LENGTH_LONG).show();
break;
default:
break;
}
return true;
}
}
How to open Navigation Drawer when click on navigation drawer icon.
I want open Navigation Drawer like this
![Navigation Drawer][1]
I added a menu but still not showing
toggle = new ActionBarDrawerToggle(
DashBordActivity.this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
if (navigationView != null) {
setupDrawerContent(navigationView);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
//#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawerLayout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void setupToolbar(String title) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(title);
toolbar.setTitleTextColor(Color.BLACK);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void setupDrawerContent(NavigationView navigationView) {
//revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawer.closeDrawers();
return true;
}
});
}
navigation drawer is not open when i click on the drawer how to solve this problem
is there any code is missing in my code.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.menu);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(START);
}
});
Try this,
<item
android:id="#+id/nav_camera"
android:icon="#drawable/ic_menu_camera"
android:title="#string/import" />
</group>
Try this:
This tutorial is very help full like:-
Add the navigation drawer layout
set icon and text in drawer layout
I refer this link
https://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
it is very helpful try this
I want to hide a menuitem from my Menu in my Navigation Drawer.
I tried using setHasOptionsMenu(true) and then adding the method
public boolean onPrepareOptionsMenu(Menu menu){
//this is where i tried to hide the item
menu.findItem(R.id.item).setVisible(false);
}
But it says that is null.
Any suggestions?
You should call setHasOptionsMenu(true) in your fragment's onCreate() method to allow your fragment to handle menu items. So you could do something like this in your fragment:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
And then, you can override onPrepareOptionsMenu method in your fragment:
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// You can hide the state of the menu item here if you call getActivity().supportInvalidateOptionsMenu(); somewhere in your code
MenuItem menuItem = menu.findItem(R.id.item);
menuItem.setVisible(false);
}
getActivity().invalidateOptionsMenu(); will call onPrepareOptionsMenu and update your menus.
I was also getting the same problem, if you are using Navigation Drawer and want to play with menu then you have to check the fragment visibility:
Please follow the steps in your Fragment, it worked for me:
1)check for the fragment visibility
boolean isMenuVisible = false;
#Override
public void setMenuVisibility(boolean menuVisible) {
try {
super.setMenuVisibility(menuVisible);
if (menuVisible && searchView != null) {
isMenuVisible = menuVisible;
}
} catch (Exception e) {
CommonUtils.firebaseCrashReport(e);
}
}
2)put this code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
2 then just check true value for isMenuVisible and play with menu
#Override public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if(isMenuVisible){
MenuItem menuItem = menu.findItem(R.id.item);
menuItem.setVisible(false);
}
}
This can be done with hiding menu item
In activity:
navigationView = (NavigationView) findViewById(R.id.nav_view);`
In fragment:
Menu nav_Menu = context.navigationView.getMenu();<br/>
nav_Menu.findItem(R.id.item_id).setVisible(false);<br>
you can pass the activity Context to fragment
As you are using a navigation drawer, you have to get MenuItem from it.
Store the NavigationView reference in onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layoutId);
...
nvDrawer = (NavigationView) findViewById(R.id.nvView);
}
Hide the MenuItem in onPrepareOptionsMenu :
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean ret = super.onPrepareOptionsMenu(menu);
MenuItem stateBtn = nvDrawer.getMenu().findItem(R.id.item);
stateBtn.setVisible(true);
return ret;
}
In onCreate() call
setHasOptionMenu(true)
and check for the null item in onPrepareOptionsMenu() like so..
#Override
public void onPrepareOptionsMenu(Menu menu) {
MenuItem item=menu.findItem(R.id.menu_id);
if(item!=null)
item.setVisible(false);
}
I have been working on this nav drawer with activites. I have a couple of activites in my projects that i want to switch between using the nav drawer.
So far I have achieved this
Create Nav drawer and Write some activities code.
Show same nav drawer in all activities.
Start a default activity when app starts.
But now my issue is that when i open my app for first time, it loads my desired activity and i can see this nav drawer. when i switch activity and press the back button, I'm getting this blank activity with nav drawer. I know its some kinda beginner level issue. But please if someone can suggest the edit. Here is my code.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
DrawerLayout drawer;
FrameLayout frameLayout;
private static boolean isLaunch = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.contant_frame);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (isLaunch) {
isLaunch = false;
startActivity(new Intent (this,MyAct.class));
}
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_manage) {
startActivity(new Intent(this,About.class));
} else if (id == R.id.nav_share) {
startActivity(new Intent(this,About.class));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I ve this same app working perfect in simple listview type nav drawer. but now i m trying to implement fancy material design.
Try overriding the onBackButtonPressed method.
Clearing/removing the onBackpressed method in MyAct and About class will bring back the last view with anything that was populated.
But if you want to open some other view or want to start new activity when back key is pressed, you can add your code here in this onBackPressed method
Hope it helps. Cheers!
In my app, I used navigation drawer. Here I listed all the items.
From the image,the items are,
Home
Filter & Sort
WishList
Shop
MyOrder
Settings
LogOut
If I am in the Fragment of Shop , I need to hide it. How to do this?
Please help me.
You can handle it in fragments onAttach method. Set the visibility of perticular item according to your need.
#Override
public void onAttach(Context context) {
super.onAttach(context);
YourActivity activity = (YourActivity)context;
NavigationView navigationView = (NavigationView) activity.findViewById(R.id.yournavigationviewid);
navigationView.getMenu().findItem(R.id.youritemid).setVisible(false);
}
inside your setNavigationItemSelectedListener where you get the selected menuItem, you can implement the code. Also you require to store the instance of the hidden menu item to make it visible later
MenuItem prevMenuItem;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if(prevMenuItem != null) prevMenuItem.setVisible(true) //making visible the previously hidden item.
menuItem.setVisible(false);
prevMenuItem = menuItem //storing the instance of currently hidden item to make it visible later.
return true;
}
});
In your public onNavigationItemSelected(MenuItem item) if you are setting one fragment then automatically drawer will hide. I'm doing like this :
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
toolbar.setTitle(item.toString());
int id = item.getItemId();
if (id == R.id.dashboard) {
fragment = new DashboardFragment();
} else if (id == R.id.manage_users) {
}else{
}
setFragmentLayout(fragment);
return true;
}
Set your fragment according to your requirements.
You can hide the drawer using mDrawerLayout.closeDrawers() in onNavigationItemSelected Listener like this:
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.navigation_item_shop:
//do your stuffs or attach fragment
mDrawerLayout.closeDrawers();
return true;
default:
return true;
}
}
}
on the fragments overide the onAttach method. Set the visibility of for items your don't need.
#Override
public void onAttach(Context context) {
super.onAttach(context);
MainActivity activity = (MainActivity)context;
NavigationView navigationView = (NavigationView) activity.findViewById(R.id.navmenu);
// hide the menu items not related to this fragment
Menu m = navigationView.getMenu();
m.findItem(R.id.first).setVisible(false);
m.findItem(R.id.second).setVisible(false);
m.findItem(R.id.therd).setVisible(false);
//and so on
}