如何将ViewPager放入片段中?

时间:2014-12-11 22:59:37

标签: android android-viewpager fragment

我的目的是在Fragment中放置一个带有2个标签的ViewPager。如果不可能,请告诉我一个替代方案...但我更喜欢使用ViewPager,因为标签之间的滑动效果。

谢谢。

1 个答案:

答案 0 :(得分:2)

选项#1:使用嵌套片段。这将要求您将minSdkVersion设置为17或更高,否则您将不得不使用Android支持包中的片段backport。 This sample app演示了如何使用backport。

简而言之,托管ViewPager的片段会将getChildFragmentManager()传递给您的FragmentPagerAdapterFragmentStatePagerAdapter

/***
  Copyright (c) 2012 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    http://commonsware.com/Android
 */

package com.commonsware.android.pagernested;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class PagerFragment extends Fragment {
  @Override
  public View onCreateView(LayoutInflater inflater,
                           ViewGroup container,
                           Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.pager, container, false);
    ViewPager pager=(ViewPager)result.findViewById(R.id.pager);

    pager.setAdapter(buildAdapter());

    return(result);
  }

  private PagerAdapter buildAdapter() {
    return(new SampleAdapter(getActivity(), getChildFragmentManager()));
  }
}

选项#2:编写自己的PagerAdapter不使用片段(或片段内部的任何内容)。然后,您不再需要嵌套片段,只需将自定义PagerAdapter与片段托管的ViewPager一起使用即可。