Hi i am a student & trying to build a app. where i want to load fragment via tapping on the navigation drawer into the main activity. i am able to attach navigation drawer to home activity. but using following code i am unable to load fragment in the activity. "loadDashboard" function is working fine, but "onNavigationItemSelected" method is not working. please help...code are bellow...
public class HomeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
loadDashboad();
NavigationView nv = findViewById(R.id.navigation_view);
nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitemdashboard:
getSupportFragmentManager().beginTransaction().replace(R.id.viewContainer, new dashboard()).commit();
break;
case R.id.menuitemlogout:
break;
case R.id.menuitemprofile:
break;
case R.id.menuitemreports:
break;
case R.id.menuitemvisits:
getSupportFragmentManager().beginTransaction().replace(R.id.viewContainer, new visits()).commit();
break;
}
return true;
}
});
}
private void loadDashboad() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
dashboard dash = new dashboard();
ft.add(R.id.viewContainer, dash);
ft.commit();
}
}
Your code is fine, what you are missing is to give the navigation menu items a function to do. Replace the following lines with the fragments that you want to add
FragmentManager fm = getSupportFragmentManager();
switch (item.getItemId()) {
case R.id.menuitemdashboard:
fm.beginTransaction().replace(R.id.viewContainer, new dashboard()).commit();
break;
case R.id.menuitemlogout:
//TODO replace logout with fragment
fm.beginTransaction().replace(R.id.viewContainer, //*log out*/).commit();
break;
case R.id.menuitemprofile:
//TODO replace profile with fragment
fm.beginTransaction().replace(R.id.viewContainer, //*profile*/).commit();
break;
case R.id.menuitemreports:
//TODO replace reports with fragment
fm.beginTransaction().replace(R.id.viewContainer, //*reports*/).commit();
break;
case R.id.menuitemvisits:
fmbeginTransaction().replace(R.id.viewContainer, new visits()).commit();
break;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.