简体   繁体   中英

How to reload/refresh a fragment from a navigation drawer

I have an android application that uses navigation drawer. I followed this tutorial Naviation Drawer Tutorial

and able to work with this on my MainActivity.java

I have this code in MainActivity to set the fragment I want to show:

public void displayView(int position) throws Exception {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
            fragment = new DashboardFragment();
            break;
        case 1:
            fragment = new EventsFragment();
            break;
        default:
            break;
        }

        if (fragment != null) {
            android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
            android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.frame_container, fragment);
            fragmentTransaction.commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    } 

Now in my EventsFragment.java I have this code to reload the fragment:

    @Override
    public void onRefreshStarted(View view) {
        MainActivity mainAct = new MainActivity();
        try {
                    // reload and set the displayValue position to 1 = EventsFragment()
            mainAct.displayView(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I'm getting this error:

java.lang.IllegalStateException: Activity has been destroyed. 

I believe I got this error in this part of code: fragmentTransaction.commit();

If you want a reference to the parent Activity , use Fragment.getActivity()

@Override
public void onRefreshStarted(View view) {
    Activity mainAct = getActivity();

    // Make sure the host Activity is infact an instance of MainActivity, and has displayView()
    if(mainAct instanceof MainActivity) {
        mainAct.displayView(1);
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM