代码是看别人的写出来的Material Design学习:TabLayout+Viewpager制作一个标签页
效果演示
顶部导航和子布局的导航都可以滑动
实现步骤
1.准备若干个Fragment,这里有四个TAB。
若要实现仅一个导航栏的布局直接参考简书上的文章。
这里给出fragment2和fragment1的xml布局,其他同2,除了1里面实现了子布局的内容
2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="218dp"
android:text="Page:"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/titile2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true"
android:textSize="50sp"
android:text="2"/>
</RelativeLayout>
1
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tab_frag"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#AAAA"
app:tabIndicatorColor="#f00"
app:tabIndicatorHeight="4dp"
app:tabMode="fixed"
app:tabSelectedTextColor="#FFFFFF"
app:tabTextColor="#FFFFFF">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/vp_frag"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</android.support.v4.view.ViewPager>
</LinearLayout>
2.其他布局文件可以看上面文章提供。
3.讲重点好了,在需要实现子局部导航栏的fragment里面的代码实现如下
public class Fragment1 extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private MyFragmentFragAdapter myFragmentFragAdapter;
@Nullable
@Override
public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment1,container,false);
tabLayout=view.findViewById(R.id.tab_frag);
viewPager=view.findViewById(R.id.vp_frag);
initView();
return view;
}
private void initView(){
myFragmentFragAdapter=new MyFragmentFragAdapter(getChildFragmentManager());
viewPager.setAdapter(myFragmentFragAdapter);
tabLayout.setupWithViewPager(viewPager);
}
}
重点在getChildFragmentManager这个方法,与在Activity有异。不然会产生滑动后返回之后丢失内容的情况。