我下载了一个关于 ViewPager 和 CirclePageIndicator 的项目。它在我的平板电脑上运行良好,它的代码是:
Test1Activity.java:
TestFragmentAdapter mAdapter;
ViewPager mPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//The look of this sample is set via a style in the manifest
setContentView(R.layout.simple_circles);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
CirclePageIndicator indicator = (CirclePageIndicator)findViewById(R.id.indicator);
indicator.setViewPager(mPager);
}
TestFragmentAdapter.java:
class TestFragmentAdapter extends FragmentPagerAdapter {
protected static final String[] CONTENT = new String[] { "Page1", "Page2", "Page3", "Page4", };
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public Fragment getItem(int position) {
return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}
@Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}}
测试片段:
public final class TestFragment extends Fragment {
private static final String KEY_CONTENT = "TestFragment:Content";
public static TestFragment newInstance(String content) {
TestFragment fragment = new TestFragment();
fragment.mContent = content;
return fragment;
}
private String mContent = "???";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
TextView text = new TextView(getActivity());
text.setGravity(Gravity.CENTER);
text.setText(mContent);
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(text);
return layout;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_CONTENT, mContent);
}}
现在我想在 Fragment 而不是 Activity 中使用这个 ViewPager,但我很困惑。TestFragmentAdapter 的构造函数接受类型为 android.support.v4.app.FragmentManager 的参数,但在片段中我只能使用 getFragmentManager() 来获取 android.app.FragmentManager 类型,因此
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
总是错的。我必须在几天内完成我的项目,所以你能告诉我如何修改我的代码以在片段中实现相同的功能吗?
谢谢!!