如何将viewpager放入android中的片段?

时间:2015-03-04 15:45:05

标签: android android-viewpager fragment

我有一项活动,我可以在此活动的framelayout上显示一些片段。 我想在片段内放一个由片段组成的viewpager而不是FragmentActivity。怎么办呢?

1 个答案:

答案 0 :(得分:58)

要让ViewPager成为片段,并让片段成为ViewPager中的页面,您需要使用嵌套片段。如果minSdkVersion为17或更高,则片段的本机实现支持嵌套片段。否则,您需要使用support-v13(或support-v4)片段的后端。

然后,您只需要将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()));
  }
}

(来自this sample project