[Android] I want to change the screen using fragments in the navigation drawer.

Asked 2 years ago, Updated 2 years ago, 106 views

public boolean onNavigationItemSelected(MenuItem item) { // // Handle navigation view item clicks here. int id = item.getItemId();

    Fragment fragment = null;
    String title = getString(R.string.app_name);

    if (id == R.id.nav_camera) {
        // // Handle the camera action
        fragment = new HomeFragment();
        title = "Homes";
    } } else if (id == R.id.nav_gallery) {
        fragment = new SettingFragment();
        title = "Settings";
    } } else if (id == R.id.nav_slideshow) {

    } } else if (id == R.id.nav_manage) {

    } } else if (id == R.id.nav_share) {

    } } else if (id == R.id.nav_send) {

    }
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_fragment_layout, fragment);
        ft.commit();
    }

    // // set the toolbar title
    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle(title);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);

    return true;
}

}

This code was implemented by Mainactivity and I wanted to move on to the fragment that was created when I pressed the item. By the way

if (id == R.id.nav_camera) { // // Handle the camera action fragment = new HomeFragment(); title = "Homes"; } } else if (id == R.id.nav_gallery) ``{ fragment = new SettingFragment(); title = "Settings"; new HomeFragment() and SettingFragment() in this part; I don't know why there's a red line on it.

android fragment

2022-09-22 21:10

1 Answers

Experience tells us what's going on the table Fragment referenced by FragmentActivity and HomeFragment/SettingFragment are presumed to be different.

If you check the imported part of the code you uploaded, I think we need to check if it's android.support.v4.app.fragment Also for HomeFragment/SettingFragment content, it would be good to check if the imported part is Android.support.v4.app.fragment.

When you use Fragment, You must use a unified combination of android.support.v4.app.fragment and android.app.fragment to use it without errors.


2022-09-22 21:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.