java.lang.IllegalStateException:Activity已被破坏导航抽屉示例

时间:2015-03-27 20:16:53

标签: android android-fragments android-activity

我正在尝试根据android教程https://developer.android.com/training/implementing-navigation/nav-drawer.html

使用抽屉布局创建导航抽屉

如果我只是创建一个类MainActivity并将DrawerItemClickListener类添加为内部类,它可以正常工作。

但是如果我在同一个包中添加DrawerItemClickListener作为新类,我会收到错误java.lang.IllegalStateException:Activity已被销毁。我将DrawerItemClickListener扩展为MainActivity以消除错误' resolve方法getFragmentManager()'和' getActionBar()'。这是我作为外部类而不是内部类的唯一区别。 以下是与教程相同的代码片段:

public class DrawerItemClickListener extends MainActivity implements ListView.OnItemClickListener {


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
    /**
     * Swaps fragments in the main content view
     */
    private void selectItem(int position) {
        // Create a new fragment and specify the planet to show based on position

        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);

        // Insert the fragment by replacing any existing fragment

            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.content_frame, fragment)
                    .commit();

            // Highlight the selected item, update the title, and close the drawer
            mDrawerList.setItemChecked(position, true);
            setTitle(mPlanetTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }


    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    @Override
    public void finish() {
        super.finish();
    }
}

0 个答案:

没有答案