关于Android中TabLayout使用总结

为了便于记忆特此写下:

效果图:

关于Android中TabLayout使用总结_第1张图片


使用步骤:

a,导入design依赖 

关于Android中TabLayout使用总结_第2张图片

b,Xml布局文件

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabIndicatorColor="@color/colorAccent"
    app:tabIndicatorHeight="1dp"
    app:tabMode="fixed"
    app:tabSelectedTextColor="@color/colorAccent"/>

<android.support.v4.view.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

c,Activity使用:

public class MainActivity extends AppCompatActivity {

    private TabLayout mTablayout;
    private ViewPager mViewPager;

    private List<Fragment> mFragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTablayout = (TabLayout) this.findViewById(R.id.tabLayout);
        mViewPager = (ViewPager) this.findViewById(R.id.viewPager);
        mFragments = new ArrayList<>();
        mFragments.add(new MyFragment());
        mFragments.add(new MyFragment());
        mFragments.add(new MyFragment());

        MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),mFragments,new String[]{"条目一","条目二","条目三"});
        mViewPager.setAdapter(adapter);
        mTablayout.setupWithViewPager(mViewPager);
    }
}

d,MyFragmentAdapter代码:

public class MyFragmentAdapter extends FragmentPagerAdapter {

    private List<Fragment> mFragmentList;
    private String[] mTitles;

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

    public MyFragmentAdapter(FragmentManager fm, List<Fragment> mFragmentList, String[] mTitles) {
        super(fm);
        this.mFragmentList = mFragmentList;
        this.mTitles = mTitles;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }
}
备注
app:tabSelectedTextColor="@color/colorAccent" //item被选中时候的颜色
app:tabIndicatorColor="@color/colorAccent" //指示线颜色

app:tabIndicatorHeight="1dp" //指示线高度

你可能感兴趣的:(关于Android中TabLayout使用总结)