如何在片段中使用ViewPager

时间:2012-04-24 14:17:25

标签: android android-fragments android-viewpager

我下载了一个关于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();
    }
}}

TestFragment:

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中使用这个ViewPager而不是Activity,但我很困惑。 TestFragmentAdapter的构造函数接受类型为android.support.v4.app.FragmentManager的参数,但是在一个片段中我只能使用getFragmentManager()来获取android.app.FragmentManager类型,因此

mAdapter = new TestFragmentAdapter(getSupportFragmentManager());

总是错的。 我必须在几天内完成我的项目,所以你能告诉我如何修改我的代码以在片段中实现相同的功能吗?

THX !!

4 个答案:

答案 0 :(得分:3)

将此代码放入MainActivity中。以下代码将在您的布局中加载片段。

第1步

Fragment fragment = new PageSlider();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content, fragment).commit();

接下来我们需要实现ViewPager

第2步

public class PageSlider extends Fragment {
public PageSlider() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
    return inflater.inflate(R.layout.page_slider, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
  super.onViewCreated(view, savedInstanceState);
  PagerSlidingTabStrip tab = (PagerSlidingTabStrip) view
.findViewById(com.akshay.protocol10.asplayer.R.id.tabs);

 ViewPager pager=(ViewPager)view  .findViewById(com.akshay.protocol10.asplayer.R.id.view_pager);
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
tab.setViewPager(pager);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}

第3步:创建适配器

    public class MyPagerAdapter extends FragmentPagerAdapter {
        private final String[] TITLES = { "Album", "Artist", "Songs", "Genre" };
        public MyPagerAdapter(FragmentManager childFragmentManager) {
      // TODO Auto-generated constructor stub
    super(childFragmentManager);
    }
    @Override
    public CharSequence getPageTitle(int position) {
    // TODO Auto-generated method stub
    return TITLES[position];
    }
    @Override
    public Fragment getItem(int index) {
    // TODO Auto-generated method stub
       Fragment fragment = null;
       if (index == 0) {
       fragment = new Albums();
       } else if (index == 1) {
       fragment = new ArtistFragment();
       } else if (index == 2) {
        fragment = new TracksFragment();
       } else if (index == 3) {
       fragment = new GenreFragment();
      }
     return fragment;
    }

    @Override
    public int getCount() {
    // TODO Auto-generated method stub
    return TITLES.length;
    }
   }

答案 1 :(得分:2)

Android不支持片段内的片段。切换ViewPager以使用不使用片段的PagerAdapter,或者不将ViewPager放入片段中。

修改

现在,Android使用Fragment.getChildFragmentManager()支持片段内的片段。看看this answer

答案 2 :(得分:0)

您是否尝试将extends Fragment替换为extends android.support.v4.app.Fragment

执行此操作时,getFragmentManager()引用android.support.v4.app.FragmentManager。

答案 3 :(得分:0)

检查片段extends class,它应该从android.support.v4.app.Fragment Not android.app.Fragment

导入