Android:使用savedInstanceState和Fragment错误

时间:2012-04-29 14:54:44

标签: android

我的代码:

主要活动

protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

..
mAdapter = new MyAdapter(getFragmentManager());
            mPager = (ViewPager) findViewById(R.id.pager);
            mPager.setAdapter(mAdapter);
            mPager.setOnPageChangeListener(new MyPageChangeListener());


private class MyPageChangeListener extends
            ViewPager.SimpleOnPageChangeListener {
        @Override
        public void onPageSelected(int position) {
            focusedPage = position;
        }
    }

public class MyAdapter extends FragmentStatePagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return qNumberSum;
    }

    @Override
    public Fragment getItem(int position) {
        ArrayListFragment alf = new ArrayListFragment();
        return alf.newInstance(position);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position,
            Object object) {
        ArrayListFragment alf = (ArrayListFragment) object;
        mCurrentView = alf.getView();

    }

}

public class ArrayListFragment extends Fragment {
    int mNum;


    /**
     * Create a new instance of CountingFragment, providing "num" as an
     * argument.
     */
    ArrayListFragment newInstance(int num) {
        ArrayListFragment f = new ArrayListFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

当savedInstanceState为null时(例如,当用户重新开始时)一切正常。 但是当不为null时,我得到了这个例外:

04-29 14:10:00.398:E / AndroidRuntime(29348):引起:android.app.Fragment $ InstantiationException:无法实例化片段com.Android.Prj.DispKl $ ArrayListFragment:确保类名存在,是公共的,并且有一个空的构造函数是公共的

为什么会这样,我该如何解决?

1 个答案:

答案 0 :(得分:2)

如果ArrayListFragmentcom.Android.Prj.DispKl的内部类,则需要static。或者,将其移动到自己独立的公共Java类中。

顺便说一句,请不要将代码放在com.Android包中。请使用您自己的域名。