fragment
package com.example.yuekaoone.fragment;
import android.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.View;
import com.example.yuekaoone.R;
import com.example.yuekaoone.adapter.ViewPagerAdapter;
import com.example.yuekaoone.adapter.ViewPagerTwoAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class BFragment extends BaseFragment {
ViewPager viewpager;
TabLayout tab;
List<Fragment> list;
ViewPagerTwoAdapter adapter;
@Override
protected void inintdata(View view) {
list = new ArrayList<>();
list.add(new B1Fragment());
list.add(new B2Fragment());
adapter = new ViewPagerTwoAdapter(getChildFragmentManager());
adapter.setdata(list);
tab.setupWithViewPager(viewpager);
viewpager.setAdapter(adapter);
}
@Override
protected void inintView(View view) {
viewpager = view.findViewById(R.id.viewpager);
tab = view.findViewById(R.id.tab);
}
@Override
protected int setcontent() {
return R.layout.fragment_b;
}
}
布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.AFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
</LinearLayout>
</FrameLayout>
adapter
package com.example.yuekaoone.adapter;
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.annotation.Nullable;
import android.support.v13.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerTwoAdapter extends FragmentPagerAdapter {
List<Fragment> list;
/**
* @param fm
* @deprecated
*/
public ViewPagerTwoAdapter(FragmentManager fm) {
super(fm);
list =new ArrayList<>();
}
public void setdata(List<Fragment> list){
this.list.clear();
this.list.addAll(list);
notifyDataSetChanged();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "第一";
case 1:
return "第二";
}
return null;
}
/**
* @param i
* @deprecated
*/
@Override
public Fragment getItem(int i) {
Fragment fragment = list.get(i);
return fragment;
}
@Override
public int getCount() {
return list.size();
}
}