问题描述
我的目的是把一个ViewPager用片段内2个选项卡。如果这是不可能的,请告诉我一个替代...但我会preFER使用ViewPager,因为标签之间的滑动效果。
My intention is to put a ViewPager with 2 tabs inside a Fragment. If it isn't possible please tell me an alternative... But I would prefer to use ViewPager, because of the swipe effect between tabs.
感谢您。
推荐答案
选项#1:使用嵌套的片段。这将需要你有你的的minSdkVersion
设置为17或更高,否则你将不得不使用的片段从Android支持包的backport。 说明如何使用反向移植。
Option #1: Use nested fragments. That will require you to have your minSdkVersion
set to 17 or higher, or you will have to use the fragments backport from the Android Support Package. This sample app demonstrates using the backport.
总之,你的片段托管 ViewPager
将通过 getChildFragmentManager()
你的 FragmentPagerAdapter
或 FragmentStatePagerAdapter
:
In short, your fragment that hosts the ViewPager
will pass getChildFragmentManager()
to your FragmentPagerAdapter
or 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
的托管由一个片段。
Option #2: Write your own PagerAdapter
that does not use fragments (or have anything inside of it managed by fragments). Then, you do not need nested fragments anymore, and you can just use your custom PagerAdapter
with a ViewPager
that is hosted by a fragment.
这篇关于我怎样才能把一个ViewPager里面的片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!