Override navigation menu selected
unknown
java
2 years ago
3.7 kB
4
Indexable
Never
Menu menu = navigationViewMain.getMenu(); final MenuItem[] previousMenuItem = {menu.findItem(R.id.menuHome)}; //tùy theo MenuItem đầu tiên sẽ khác nhau previousMenuItem[0].setChecked(true); //set trạng thái checked cho MenuItem đầu tiên navigationViewMain.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Fragment selectedFragment = null; Intent intent = null; switch (item.getItemId()) { case R.id.menuLogin: { intent = new Intent(MainActivity.this, LoginActivity.class); startActivityForResult(intent, 1); break; } case R.id.menuRegister: { intent = new Intent(MainActivity.this, SignUpActivity.class); startActivityForResult(intent, 2); break; } case R.id.menuLogout: { SharedPreferences sharedPreferences = getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove("user_id"); editor.apply(); setItemInMenuWithLogin(); break; } case R.id.menuHome: { selectedFragment = new HomeFragment(); break; } case R.id.menuProfile: { selectedFragment = new ProfileFragment(); break; } case R.id.menuCart: { selectedFragment = new CartFragment(); break; } case R.id.menuNotify: { selectedFragment = new NotificationFragment(); break; } case R.id.menuMessage: { selectedFragment = new MessageFragment(); break; } case R.id.menuOrderHistory: { selectedFragment = new OrderHistoryFragment(); break; } case R.id.menuSetting: { selectedFragment = new SettingFragment(); break; } default: break; } // Highlight the selected item in the menu if(item.getItemId() != R.id.menuLogin && item.getItemId() != R.id.menuRegister) { previousMenuItem[0].setChecked(false); //bỏ trạng thái check của MenuItem trước đó item.setChecked(true); previousMenuItem[0] = item; //cập nhật MenuItem trước đó } // Replace the fragment or start the activity if (selectedFragment != null) { getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, selectedFragment).commit(); } // Close the navigation drawer drawerLayoutMain.closeDrawer(GravityCompat.START); return true; } });