项目单击导航抽屉后,片段不会更改

时间:2017-02-12 09:56:19

标签: android android-studio android-fragments fragment navigation-drawer

我正在构建一个包含NavigationDrawer的应用,可以在片段之间导航。 出于某种原因,当按下导航抽屉中的任何项目时,该项目仅标记自己并且不会更改片段(尝试调试但项目点击不会调用函数)

首次点击时未加载fragment ..我必须按两次才能重新加载fragment

主要活动:

public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawer;
private View navHeader;
private ImageView imgNavHeaderBg, imgProfile;
private TextView txtName, txtCity;
private Toolbar toolbar;
private FloatingActionButton fab;

// urls to load user profile & background
private static final String urlNavHeaderBg = "";
private static final String urlProfileImg = "";

//current menu pressed
public static int navItemIndex = 0;

//tags for fragments
private static final String TAG_HOME = "home";
private static final String TAG_PROFILE = "profile";
private static final String TAG_RATEUS = "rate us";
private static final String TAG_SCORE = "rate score";
private static final String TAG_NOTIFICATIONS = "notifications";
private static final String TAG_SETTINGS = "settings";
public static String CURRENT_TAG = TAG_HOME;

private String[] activityTitles;
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mHandler = new Handler();
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    fab = (FloatingActionButton) findViewById(R.id.fab);

    //nav view header
    navHeader = navigationView.getHeaderView(0);
    txtName = (TextView) navHeader.findViewById(R.id.name);
    txtCity = (TextView) navHeader.findViewById(R.id.city);
    imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg);
    imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile);

    //load the toolbar titles
    activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Make action here", Snackbar.LENGTH_LONG).setAction("Action", null).show();
        }
    });

    //load the navigator header data
    loadNavHeader();

    //initialize nav menu
    setUpNavigationView();

    if (savedInstanceState == null) {
        navItemIndex = 0;
        CURRENT_TAG = TAG_HOME;
        loadHomeFragment();
    }
}

private void loadNavHeader() {
    txtName.setText("My Name");
    txtCity.setText("Somewhere, Europe");

    Glide.with(this).load(urlNavHeaderBg).crossFade().diskCacheStrategy(DiskCacheStrategy.ALL).into(imgNavHeaderBg);
    Glide.with(this).load(urlProfileImg).thumbnail(0.5f).bitmapTransform(new CircleTransform(this)).diskCacheStrategy(DiskCacheStrategy.ALL).into(imgProfile);

    navigationView.getMenu().getItem(4).setActionView(R.layout.menu_dot);
}

private void loadHomeFragment() {
    selectNavMenu();
    setToolBarTitle();

    if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
        drawer.closeDrawers();
        toggleFab();
        return;
    }
    Runnable mPendingRunnable = new Runnable() {
        @Override
        public void run() {
            Fragment fragment = getHomeFragment();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
            fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
            fragmentTransaction.commitAllowingStateLoss();
        }
    };
    if (mPendingRunnable != null) {
        mHandler.post(mPendingRunnable);
    }
    toggleFab();

    drawer.closeDrawers();
    invalidateOptionsMenu();
}

private Fragment getHomeFragment() {
    switch (navItemIndex) {
        case 0:
            HomeFragment homeFragment = new HomeFragment();
            return homeFragment;
        case 1:
            ProfileFragment profileFragment = new ProfileFragment();
            return profileFragment;
        case 2:
            RateusFragment rateusFragment = new RateusFragment();
            return rateusFragment;
        case 3:
            ScoreFragment scoreFragment = new ScoreFragment();
            return scoreFragment;
        case 4:
            NotificationsFragment notificationsFragment = new NotificationsFragment();
            return notificationsFragment;
        case 5:
            SettingsFragment settingsFragment = new SettingsFragment();
            return settingsFragment;
        default:
            return new HomeFragment();
    }
}

private void setToolBarTitle() {
    getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}

private void selectNavMenu() {
    navigationView.getMenu().getItem(navItemIndex).setCheckable(true);
}

private void setUpNavigationView() {
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.nav_home:
                    navItemIndex = 0;
                    CURRENT_TAG = TAG_HOME;
                    break;
                case R.id.nav_profile:
                    navItemIndex = 1;
                    CURRENT_TAG = TAG_PROFILE;
                    break;
                case R.id.nav_rateus:
                    navItemIndex = 2;
                    CURRENT_TAG = TAG_RATEUS;
                    break;
                case R.id.nav_score:
                    navItemIndex = 3;
                    CURRENT_TAG = TAG_SCORE;
                    break;
                case R.id.nav_notifications:
                    navItemIndex = 4;
                    CURRENT_TAG = TAG_NOTIFICATIONS;
                    break;
                case R.id.nav_settings:
                    navItemIndex = 5;
                    CURRENT_TAG = TAG_SETTINGS;
                    break;
                case R.id.nav_about_us:
                    startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
                    drawer.closeDrawers();
                    return true;
                case R.id.nav_terms:
                    startActivity(new Intent(MainActivity.this, TermsActivity.class));
                    drawer.closeDrawers();
                    return true;
                default:
                    navItemIndex = 0;
            }
            if (menuItem.isChecked()) {
                menuItem.setChecked(false);
            } else {
                menuItem.setChecked(true);
            }
            menuItem.setChecked(true);

            return true;
        }
    });

    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            //when nav closed this will triggered - leaving blank so nothing won't happen
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            //when nav opened this will triggered - leaving blank so nothing won't happen
            super.onDrawerOpened(drawerView);
        }
    };
    drawer.addDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
}

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawers();
        return;
    }
    if (shouldLoadHomeFragOnBackPress) {
        if (navItemIndex != 0) {
            navItemIndex = 0;
            CURRENT_TAG = TAG_HOME;
            loadHomeFragment();
            return;
        }
    }
    super.onBackPressed();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (navItemIndex == 0) {
        getMenuInflater().inflate(R.menu.main, menu);
    }
    if (navItemIndex == 4) {
        getMenuInflater().inflate(R.menu.notifications, menu);
    }
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_logout) {
        Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show();
        return true;
    }
    if (id == R.id.action_mark_all_read) {
        Toast.makeText(getApplicationContext(), "All marked as read!", Toast.LENGTH_LONG).show();
    }
    if (id == R.id.action_clear_notifications) {
        Toast.makeText(getApplicationContext(), "All Cleared!", Toast.LENGTH_LONG).show();
    }
    return super.onOptionsItemSelected(item);
}

private void toggleFab() {
    if (navItemIndex == 0)
        fab.show();
    else
        fab.hide();
}

}

activity_main.xml中:

<?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_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    tools:context=".activity.MainActivity">
<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

1 个答案:

答案 0 :(得分:1)

代码有几个问题:

确保你在开关中添加break:

case R.id.nav_about_us:
    startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
    drawer.closeDrawers();
    break;  //add break
case R.id.nav_terms:
    startActivity(new Intent(MainActivity.this, TermsActivity.class));
    drawer.closeDrawers();
    break;  
default:
    navItemIndex = 0;
     break;

你的片段没有加载,因为你没有正确调用函数:

在你的Switch案例中

case R.id.nav_home:
    navItemIndex = 0;
    CURRENT_TAG = TAG_HOME;
    Fragment fragment = getHomeFragment();  //get fragment based on index
    ReplaceFragment(fragment);  //now replace them and load new one
    drawer.closeDrawers();
    break;

ReplaceFragment方法中写道:

public void ReplaceFragment(Fragment r_fragment) {
    if (r_fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame, r_fragment).commit();

    } else {
        // error in creating fragment
    }

}

还覆盖以下方法:

 @Override
public void onDrawerOpened(View drawerView) {
    super.onDrawerOpened(drawerView);
    drawerView.bringToFront();  //add this two lines
    drawerView.requestLayout();
}

 @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        actionBarDrawerToggle.syncState();
    }