如何从导航抽屉重新加载/刷新片段

时间:2014-04-27 14:37:25

标签: java android android-fragments navigation-drawer

我有一个使用导航抽屉的Android应用程序。 我按照本教程Naviation Drawer Tutorial

进行了操作

并且能够在我的 MainActivity.java

上使用它

我在 MainActivity 中有此代码来设置我想要显示的片段:

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");
        }
    } 

现在我的 EventsFragment.java 我有这段代码重新加载片段:

    @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();
        }
    }

我收到此错误:

java.lang.IllegalStateException: Activity has been destroyed. 

我相信我在这部分代码中遇到了这个错误: fragmentTransaction.commit();

1 个答案:

答案 0 :(得分:0)

如果您想要引用父Activity,请使用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);
    }
}