【问题标题】:How can I put a ViewPager inside a Fragment?如何将 ViewPager 放入片段中?
【发布时间】:2014-12-11 22:59:37
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: android android-viewpager fragment


    【解决方案1】:

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

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

    /***
      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 一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多