getSupportFragmentManager

getSupportFragmentManager

我正在尝试使用fragment实现swipe视图。
但对我来说,扩展简单活动而不是片段活动是非常重要的。
在下面编写的代码中,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;
    }
}
}

最佳答案

这个错误是不言而喻的。getSupportFragmentManager()仅为FragmentActivity类定义。无论您多么希望或需要调用该方法,它根本不存在于普通活动中。
另请参见:Difference between Activity and FragmentActivityDifference between Fragment and FragmentActivity

关于android - 从 Activity 调用getSupportFragmentManager()时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15980722/

10-08 23:28