TabLayout和ViewPager结合使用

TabLayout和ViewPager结合使用,比起上一篇RadioGroup和ViewPager结合使用要简单的多。
MainActivity

package com.example.viewpager;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import com.example.viewpager.adapter.MyFragmentPagerAdapter;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 滑动页
 */
public class MainActivity extends AppCompatActivity {

    @Bind(R.id.viewpager)
    ViewPager viewpager;
    @Bind(R.id.tableLayout)
    TabLayout tableLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        viewpager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager()));
        tableLayout.setupWithViewPager(viewpager);

    }
}

MyFragmentPagerAdapter
适配器中的数据 fragment不是从activity中传过来的,这样写不好

package com.example.viewpager.adapter;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.example.viewpager.Fragment.ElementaryFragment;
import com.example.viewpager.Fragment.MapFragment;
import com.example.viewpager.Fragment.ZipFragment;

/**
 * Created by HASEE on 2017/6/7 14:13
 *
 * fragment不是从activity中传过来的,这样写不好
 */

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    public MyFragmentPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new ElementaryFragment();
            case 1:
                return new MapFragment();
            case 2:
                return new ZipFragment();
            default:
                return new ElementaryFragment();
        }
    }

    @Override
    public int getCount() {
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "基本";
            case 1:
                return "转换";
            case 2:
                return "压合";
            default:
                return "基本";
        }
    }
}

布局如下




    

    

    

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