ViewPager与FragmentPagerAdapter一起作为片段本身?

时间:2014-07-31 11:54:51

标签: android android-fragments

具有FragmentPagerAdapter的View Pager是否可能是它自己的片段而不是片段活动?

这是我的意思的图片。

http://d3a0c3fa3t59bz.cloudfront.net/wordpress/wp-content/uploads/2013/01/timetable1.png

请注意,在最左侧是星期四和星期五的视图寻呼机。这是我正在寻找片段视图寻呼机作为片段本身的那种安排。

如果有人可以发布示例,建议或提供链接来实现这一点,我将非常感激。先感谢您。

1 个答案:

答案 0 :(得分:2)

是的,尽管你必须使用嵌套片段,这给许多开发人员带来了麻烦。

This sample project演示了它的工作原理。以下是托管PagerFragment的示例中的ViewPager

/***
  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()));
  }
}

请注意来自SampleAdapter的{​​{1}} getChildFragmentManager()是如何传递的,而不是Fragment。这允许getFragmentManager()使用片段,片段将嵌套在外部片段(SampleAdapter)中。除此之外,PagerFragment实现的其余部分应与ViewPager直接由活动托管相同。