3

我正在尝试使用片段实现滑动视图。但对我来说扩展简单活动而不是片段活动非常重要。我在下面编写的代码中遇到 getSupportFragmentManager() 错误:

public class CollectionDemoActivity extends Activity {

DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;

ViewPager mViewPager;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_collection_demo);


    mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}

public static class DemoCollectionPagerAdapter extends FragmentStatePagerAdapter {

    public DemoCollectionPagerAdapter(FragmentManager fm) {
        super(fm);
        //int x=10;
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new DemoObjectFragment();
        Bundle args = new Bundle();
        args.putInt(DemoObjectFragment.ARG_OBJECT, i + 10); 
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        // For this contrived example, we have a 100-object collection.
        return 100;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "OBJECT " + (position + 1);
    }
}


public static class DemoObjectFragment extends Fragment {

    public static final String ARG_OBJECT = "object";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
        Bundle args = getArguments();
        ((TextView) rootView.findViewById(android.R.id.text1)).setText(
                Integer.toString(args.getInt(ARG_OBJECT)));
        return rootView;
    }
}
}
4

1 回答 1

5

这个错误是不言自明的。getSupportFragmentManager()仅为FragmentActivity类定义。无论您多么想或需要调用该方法,对于普通的活动来说,它根本不存在。

另请参阅:Activity 和 FragmentActivity之间的差异和 Fragment和FragmentActivity 之间的差异

于 2013-04-12T21:11:52.880 回答