TabLayout ViewPager的使用

1.布局文件:

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context=".MainActivity">

   

        android:id="@+id/tab"

        app:tabGravity="fill"

       app:tabTextAppearance="@style/TabLayoutTextStyle"

        android:layout_width="match_parent"

        android:layout_height="50dp">

   

        android:id="@+id/vp"

        android:layout_width="match_parent"

        android:layout_height="0dp"

        android:layout_weight="1">

   

2.actvivty主页


public class MainActivity extends AppCompatActivity {

    private ViewPager vp;

    private ArrayList fraglist;

    private ArrayList tablist;

    private TabLayout tab;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        tab = (TabLayout) findViewById(R.id.tab);

        vp = (ViewPager) findViewById(R.id.vp);

        fraglist = new ArrayList<>();

        fraglist.add(new Frag01());

        fraglist.add(new Frag02());

        fraglist.add(new Frag03());

        fraglist.add(new Frag04());

        tablist = new ArrayList<>();

        tablist.add("页面1");

        tablist.add("页面2");

        tablist.add("页面3");

        tablist.add("页面4");

        MyPageAdapter myPageAdapter = new MyPageAdapter(getSupportFragmentManager(), fraglist, tablist);

        vp.setAdapter(myPageAdapter);

        tab.setupWithViewPager(vp);

    }

}

3.FragmentPagerAdapter 适配器

public class MyPageAdapter extends FragmentPagerAdapter {

    private Context context;

    private ArrayList list;

    private ArrayList lists;

    public MyPageAdapter(FragmentManager fm, ArrayList list, ArrayList lists) {

        super(fm);

        this.list = list;

        this.lists = lists;

    }

    @Override

    public Fragment getItem(int i) {

        return list.get(i);

    }

    @Override

    public int getCount() {

        return list.size();

    }

    @Nullable

    @Override

    public CharSequence getPageTitle(int position) {

        return lists.get(position);

    }

你可能感兴趣的:(TabLayout ViewPager的使用)