java.lang.IllegalStateException:片段事务期间活动已被销毁

时间:2016-06-28 07:28:28

标签: android android-fragments

使用片段时我遇到以下异常: java.lang.IllegalStateException:活动已被销毁

代码如下:

 try {
        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);

        } else {
            Log.e("MainActivity", "Error in creating fragment");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

DrawerItemClickListener.java

public class DrawerItemClickListener extends FragmentActivity implements ListView.OnItemClickListener {
    private ListView mDrawerList;
    private DrawerLayout mDrawerLayout;
    private String[] mNavigationDrawerItemTitles;


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }


    private void selectItem(int position) {

        Fragment fragment = null;

        switch (position) {
            case 0:
                fragment = new ActivitDiagnosisFragment();
                break;
            case 1:
                fragment = new ActivitDiagnosisFragment();
                break;
        //  case 2:
        //      fragment = new HelpFragment();
        //      break;

            default:
                break;
        }


        try {
            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

                mDrawerList.setItemChecked(position, true);
                mDrawerList.setSelection(position);
                getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
                mDrawerLayout.closeDrawer(mDrawerList);


            } else {
                Log.e("MainActivity", "Error in creating fragment");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

0 个答案:

没有答案