TabLayout使用

第一步:输入design就能出来
TabLayout使用_第1张图片

布局:




    
    


主页面的代码

package com.bawei.tab.frag;

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.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bawei.tab.R;
import com.bawei.tab.adapter.MyPagerAdapter;
import com.bawei.tab.frag.tab.TabOne;
import com.bawei.tab.frag.tab.TabTwo;

import java.util.ArrayList;


public class FragOnew extends Fragment {

    private TabLayout tab;
    private ViewPager pager;
    private ArrayList arr;
    private ArrayList title;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_one, container, false);
        //第二步:控件TabLayout
        tab = view.findViewById(R.id.tab);
        pager = view.findViewById(R.id.pager);
        //第三步:创建Fragment集合
        arr = new ArrayList<>();
        arr.add(new TabOne());
        arr.add(new TabTwo());
        //第四步:创建文本集合
        title = new ArrayList<>();
        title.add("one");
        title.add("two");
        //第五步:设置适配器
        pager.setAdapter(new MyPagerAdapter(getActivity().getSupportFragmentManager(),arr, title));
        //第七步:绑定
        tab.setupWithViewPager(pager);//此方法就是让tablayout和ViewPager联动
        return view;
    }
}

适配器:

package com.bawei.tab.adapter;

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

import java.util.ArrayList;


public class MyPagerAdapter extends FragmentPagerAdapter {
    private ArrayList arr;
    private ArrayList tit;
    public MyPagerAdapter(FragmentManager fm, ArrayList arr,ArrayList tit) {
        super(fm);
        this.arr=arr;
        this.tit=tit;
    }

    @Override
    public Fragment getItem(int i) {
        return arr.get(i);
    }

    @Override
    public int getCount() {
        return arr.size();
    }
    //此方法用来显示tab上面的名字

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return tit.get(position);
    }
}

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