//布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout
android:id="@+id/tab"
android:layout_width=“match_parent”
android:layout_height=“0dp”
android:layout_weight=“1”/>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width=“match_parent”
android:layout_height=“0dp”
android:layout_weight=“9”>
</android.support.v4.view.ViewPager>
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.tablatout.R;
import com.example.tablatout.madapter.HomeAdapter;
public class Fragmentone extends Fragment {
private ViewPager pager;
private TabLayout tab;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragmentone,container,false);
pager = view.findViewById(R.id.pager);
tab = view.findViewById(R.id.tab);
pager.setAdapter(new HomeAdapter(getChildFragmentManager()));
tab.setupWithViewPager(pager);
return view;
}
}
//adapterhome
package com.example.tablatout.madapter;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.example.tablatout.fragment.FragmentBlank;
import com.example.tablatout.fragment.FragmentHome;
public class HomeAdapter extends FragmentPagerAdapter {
public HomeAdapter(FragmentManager fm) {
super(fm);
}
private String[] name=new String[]{
“关注”,“推荐”
} ;
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new FragmentHome();
default:
return new FragmentBlank();
}
}
@Override
public int getCount() {
return name.length;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return name[position];
}
}