When I'm trying to switch between activies using intent in "switch case" the following error I got:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation2);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_home:
return true;
case R.id.ic_wallet:
Intent intent_wallet = new Intent(MainActivity.this,Wallet.class);
startActivity(intent_wallet);
return true;
case R.id.ic_status:
Intent intent_status = new Intent(MainActivity.this,Status.class);
startActivity(intent_status);
return true;
case R.id.ic_history:
Intent intent_history = new Intent(MainActivity.this,History.class);
startActivity(intent_history);
return true;
}
return false;
}
};
}
activity_main.xml
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.praveen.gupta.frontpage.MainActivity">
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#drawable/white_grey_border_top"
app:labelVisibilityMode="labeled"
app:menu="#menu/navigation" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:id="#+id/ic_home"
android:icon="#drawable/ic_home_black_24dp"
android:title="Home"
/>
<item
android:id="#+id/ic_wallet"
android:icon="#drawable/ic_account_balance_wallet_black_24dp"
android:title="Wallet"
/>
<item
android:id="#+id/ic_status"
android:icon="#drawable/ic_star_border_black_24dp"
android:title="Status"
/>
<item
android:id="#+id/ic_history"
android:icon="#drawable/ic_history_black_24dp"
android:title="History"
/>
</menu>
mOnNavigationItemSelectedListener is null thats why you are getting error.You are initializing outside on oncreate method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//move `mOnNavigationItemSelectedListener` code here .
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_home:
return true;
case R.id.ic_wallet:
Intent intent_wallet = new Intent(MainActivity.this,Wallet.class);
startActivity(intent_wallet);
return true;
case R.id.ic_status:
Intent intent_status = new Intent(MainActivity.this,Status.class);
startActivity(intent_status);
return true;
case R.id.ic_history:
Intent intent_history = new Intent(MainActivity.this,History.class);
startActivity(intent_history);
return true;
}
return false;
}
};
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation2);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
Related
I have created a DrawerLayout and it works fine. But I want it to close when the user touches the background. This can be implemented with a DrawerLayout with listView but here i'm using a NavigationView. So is there a way to accomplish this?
Here is the menu layout for the NavigationView
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/home" android:title="Home Parent" android:icon="#drawable/ic_home_black"/>
<item android:id="#+id/send" android:title="Send" android:icon="#drawable/ic_send_black"/>
<item android:id="#+id/add" android:title="Add" android:icon="#drawable/ic_add_black"/>
</menu>
Here is the java code
public class ParentActivity extends AppCompatActivity {
private NavigationView mNavigationView;
private User mCurrentUser;
private UserLocalStore mUserLocalStore;
private CircleImageView mProfilePic;
private TextView mProfileName;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parent);
mUserLocalStore = new UserLocalStore(this);
mCurrentUser = mUserLocalStore.getUserDetails();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mNavigationView = (NavigationView)findViewById(R.id.navigationView);
setNavigationViewMenu(mCurrentUser.userType);
mProfileName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.profileName);
mProfileName.setText(mCurrentUser.getName());
mProfilePic = (CircleImageView) mNavigationView.getHeaderView(0).findViewById(R.id.circleImageProfile);
Picasso.with(this).load("https://www.sonypark360.net/wp-content/uploads/2017/08/profile-pictures.png").into(mProfilePic);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
mDrawerLayout.closeDrawers();
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
private void setNavigationViewMenu(String userType) {
switch (userType){
case "s":
mNavigationView.inflateMenu(R.menu.menu_student_navigation_drawer);
break;
case "pa":
mNavigationView.inflateMenu(R.menu.menu_parent_navigation_drawer);
break;
case "pr":
mNavigationView.inflateMenu(R.menu.menu_principal_navigation_drawer);
break;
case "t":
mNavigationView.inflateMenu(R.menu.menu_teacher_navigation_drawer);
break;
}
}
}
Here is the DrawerLayout code
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mlpj.www.morascorpions.ParentActivity">
<android.support.design.widget.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header_layout"
>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
I have also looked into this question, but it does not solve my problem
Try this
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Rect viewRect = new Rect();
mNavigationView.getGlobalVisibleRect(viewRect);
if (!viewRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
//hide your navigation view here.
}
return super.dispatchTouchEvent(ev);;
}
I had a menu in my app and it works correctly, now I add a TabLayout and the menu options does not respond to user click now no more.
Here is my activity_main.xml code:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include layout="#layout/toolbar"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewPaper"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
My Activity onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
itemAdapter = new ClientAdapter(this, null);
tab = (TabLayout)findViewById(R.id.tab);
paper = (ViewPager)findViewById(R.id.viewPaper);
paperAdapter = new ViewPaperAdapter(getSupportFragmentManager());
HomeFragment homeFragment = new HomeFragment();
DoneFragment doneFragment = new DoneFragment();
paperAdapter.addFrament(homeFragment, "Home");
paperAdapter.addFrament(doneFragment, "Done");
paper.setAdapter(paperAdapter);
tab.setupWithViewPager(paper);
}
onCreateOptionMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
searchView = (SearchView)MenuItemCompat.getActionView(menuItem);
searchView.setOnQueryTextListener(this);
return super.onCreateOptionsMenu(menu);
}
And onOptionItemSelected method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.refresh:
//Check the internet connection
if(Util.isConnected(this)){
// showProgress();
//Check if there is not pending item
sincronize(this);
dbManager.borrar();
new HomeFragment().getTarjetas();
}else{
Toast.makeText(this, "No hay conexion a internet.", Toast.LENGTH_LONG).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
The menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="developer.technologies.agilisa.acardmobile.MainActivity">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
android:orderInCategory="100"
android:title="#string/Search"
app:showAsAction="always|collapseActionView"
android:elevation="8dp"
app:actionViewClass="android.support.v7.widget.SearchView"/>
<item
android:id="#+id/refresh"
android:title="#string/refresh"
android:icon="#drawable/refresh"
android:orderInCategory="200"
app:showAsAction="always|collapseActionView"/>
<item
android:id="#+id/cerrar"
android:orderInCategory="10"
app:showAsAction="never"
android:title="#string/cerrar_session"/>
Can some one help me to solve that?
Try this changes:
Change Your Root layout To LinearLayout or Coordinator Layout-- As framelayout sometimes consume the click event of items under it.
1.in onCreateOptionsMenu()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Your code
return true;
}
2.And in onOptionsItemSelected() add return true
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.refresh:
// your code
return true; //add this
default:
return super.onOptionsItemSelected(item);
}
}
I can't seem to figure this one out. I have MainActivity and created SecondActivity and ThirdActivity that I want to be able to navigate to.
I'm using BottomNavigation in my MainActivity to navigated between activities:
public class MainActivity extends AppCompatActivity {
protected BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_menuItem1:
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
return true;
case R.id.navigation_menuItem2:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
return true;
case R.id.navigation_menuItem3:
Intent intent = new Intent(MainActivity.this, ThirdActivity.class);
startActivity(intent);
return true;
}
return false;
}
};
navigationView = (BottomNavigationView) findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
Any clue why it's not switching pages/activities?
EDIT: Added these lines to make it work:
protected BottomNavigationView navigationView;
AND
navigationView = (BottomNavigationView) findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
Thanks for the help!
just in case you missed something, make sure you didn't forget something:
Create a BottomNavigationView in xml of your layout:
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="0dp"
android:layout_marginStart="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
Create a file here navigation.xml in menu resource folder. This file is used for providing the MenuItems in BottomNavigationView
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/navigation_menuItem1"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/menuItem1" />
<item
android:id="#+id/navigation_menuItem2"
android:icon="#drawable/ic_dashboard_black_24dp"
android:title="#string/menuItem2" />
<item
android:id="#+id/navigation_menuItem3"
android:icon="#drawable/ic_notifications_black_24dp"
android:title="#string/menuItem3" />
</menu>
Now lets set the listener for the Click Events OnNavigationItemSelectedListener and OnNavigationItemReselectedListener on Menu Items:
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_menuItem1:
return true;
case R.id.navigation_menuItem2:
return true;
case R.id.navigation_menuItem3:
return true;
}
return true;
}
};
private BottomNavigationView.OnNavigationItemReselectedListener mOnNavigationItemReselectedListener = new BottomNavigationView.OnNavigationItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_menuItem1:
Log.d(TAG, "navigation_menuItem1 Reselected ===");
break;
case R.id.navigation_menuItem2:
Log.d(TAG, "navigation_menuItem2 Reselected ===");
break;
case R.id.navigation_menuItem3:
Log.d(TAG, "navigation_menuItem3 Reselected ===");
break;
}
}
};
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
bottomNavigationView.setOnNavigationItemReselectedListener(mOnNavigationItemReselectedListener);
EDIT
Add this to your onCreate()
BottomNavigationView bottomNavigationView;
bottomNavigationView = findViewById(R.id.navigation);
When the app first starts up, it checks the last menuitem as if it was clicked. It displays the first menuitem content. In Android Studio, no errors, warnings, or logs are displayed that hint at anything going wrong.
Once the app is running, if I click on any of the other menuitems, it works normal. I can click on each of the menuitems and the correct fragment populates accordingly.
Here is MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
/* This is never called on start up */
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_home:
frag = HomeFragment.newInstance();
break;
case R.id.menu_archives:
frag = ArchivesFragment.newInstance();
break;
case R.id.menu_inspirational:
frag = InspirationalFragment.newInstance();
break;
case R.id.menu_search:
frag = SearchFragment.newInstance();
break;
}
// update selected item
mSelectedItem = item.getItemId();
// unchecked the other items.
//THIS LINE HERE
for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == mSelectedItem);
}
updateToolbarText(item.getTitle());
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
private void updateToolbarText(CharSequence text) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(text);
}
}
Here is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ourdailystrength.mobile.android.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#f1f1f1">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
design:menu="#menu/bottom_nav_items" />
</LinearLayout>
Here is bottom_nav_items.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_home"
android:title="#string/menu_home"
android:icon="#drawable/ic_home_black_48dp"
android:checked="true" <!-- Doesn't matter if this line is included or not -->
app:showAsAction="ifRoom"/>
<item
android:id="#+id/menu_archives"
android:title="#string/menu_archives"
android:icon="#drawable/ic_archive_black_48dp"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/menu_search"
android:title="#string/menu_search"
android:icon="#drawable/ic_search_black_48dp"
app:showAsAction="ifRoom"/>
<item
android:id="#+id/menu_inspirational"
android:title="#string/menu_inspirational"
android:icon="#drawable/ic_photo_black_48dp"
app:showAsAction="ifRoom"/>
</menu>
Here is a screenshot of when it first boots up:
Why is the last menuitem being checked and not the first menuitem?
EDIT:
So, from answers given below, I made this change and it works:
private void selectFragment(MenuItem item) {
Fragment frag = null;
// update selected item
mSelectedItem = item.getItemId();
// unchecked the other items.
for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(false);
}
// init corresponding fragment
switch (mSelectedItem) {
case R.id.menu_home:
frag = HomeFragment.newInstance();
mBottomNav.getMenu().findItem(R.id.menu_home).setChecked(true);
break;
case R.id.menu_archives:
frag = ArchivesFragment.newInstance();
mBottomNav.getMenu().findItem(R.id.menu_archives).setChecked(true);
break;
case R.id.menu_inspirational:
frag = InspirationalFragment.newInstance();
mBottomNav.getMenu().findItem(R.id.menu_inspirational).setChecked(true);
break;
case R.id.menu_search:
frag = SearchFragment.newInstance();
mBottomNav.getMenu().findItem(R.id.menu_search).setChecked(true);
break;
}
updateToolbarText(item.getTitle());
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
Why would the THIS LINE HERE in the above code cause it to do this weird error?
Hope this may help you to resolve your issue.
Call this method whenever you change the Fragment. Pass checkedcolor and unchecked color according to your needs.
private void changeMenuItemCheckedStateColor(int checkedColor, int uncheckedColor) {
int[][] states = new int[][]{
new int[]{-android.R.attr.state_checked}, // unchecked
new int[]{android.R.attr.state_checked}, // checked
};
int[] colors = new int[]{
uncheckedColor,
checkedColor
};
ColorStateList colorStateList = new ColorStateList(states, colors);
bottomNavigationView.setItemTextColor(colorStateList);
bottomNavigationView.setItemIconTintList(colorStateList);
}
There is 2 Solutions
1) Use Group
<group android:checkableBehavior="single">
<item .../>
<item .../>
<item .../>
</group>
2) Do it by programmatically
Menu bottomMenu;
BottomNavigationView bottomNavigationMenu = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomMenu = navigation.getMenu();
bottomMenu.findItem(R.id.menu_home).setChecked(true);
Hope it will help , If you have any queries please comment.
Remove below code:
// unchecked the other items.
for (int i = 0; i < mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == mSelectedItem);
}
and give tint color in BottomNavigationView:
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
app:itemIconTint="#drawable/nav_item_color_state"
design:menu="#menu/bottom_nav_items" />
I have this menu layout "navigation_menu.xml":
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/item1"
android:title="#string/item1"/>
<item
android:id="#+id/item2"
android:title="#string/item2"/>
<item
android:id="#+id/item3"
android:title="#string/item3"/>
</menu>
My main activity layout "activity_main.xml" is this:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:layout_gravity="start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
And this is the Java code of the main activity where I initialize the drawer:
private DrawerLayout drawer_layout;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
drawer_layout = (DrawerLayout)findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer_layout, R
.string.open_drawer, R.string.close_drawer);
drawer_layout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
The drawer opens and closes correctly, but I don't know how to do something when an item is clicked, for example showing a log.
Does anyone know?
Thanks
Use onNavigationItemSelected() method to handle Navigation Drawer Item Click. See Below Code.
private NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// ...
mNavigationView = (NavigationView) findViewById(R.id.nav_view);
mNavigationView.setNavigationItemSelectedListener(this);// you need to set Listener.
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item)
{
// mDrawer.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.item1: {
}
break;
case R.id.item2: {
}
break;
case R.id.item3: {
}
break;
}
return true;
}