android TabLayout+ViewPager配合使用

1.在項(xiàng)目app下的Module中添加依賴

compile 'com.android.support:design:25.2.0'

2.相應(yīng)的布局文件

<android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white"/>
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0.5px"
        android:background="@color/line_color"
        ></LinearLayout>
<android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/toolBarColor"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/toolBarColor"
        app:tabTextColor="#000000"
        />        

3.構(gòu)建adapter

public class MyPagerAdapter extends FragmentPagerAdapter {
    private Context context;
    private List<Fragment> fragmentList;
    private List<String> list_Title;
    public MyPagerAdapter(FragmentManager fm,Context context,List<Fragment> fragmentList,List<String> list_Title) {
        super(fm);
        this.context = context;
        this.fragmentList = fragmentList;
        this.list_Title = list_Title;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }
    @Override
    public int getCount() {
        return list_Title.size();
    }
    /**
     * //此方法用來(lái)顯示tab上的名字
     * @param position
     * @return
     */
    @Override
    public CharSequence getPageTitle(int position) {
        return list_Title.get(position);
    }

4.tablayout和ViewPager聯(lián)動(dòng)

 fragmentList = new ArrayList<>();
        list_Title = new ArrayList<>();
        fragmentList.add(new OneFragment());
        fragmentList.add(new TwoFragment());
        list_Title.add("one");
        list_Title.add("two");
        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(),HelpCenterActivity.this,fragmentList,list_Title));
tablayout.setupWithViewPager(viewpager);//此方法就是讓tablayout和ViewPager聯(lián)動(dòng)

效果圖如下


這里寫圖片描述

詳細(xì)代碼已經(jīng)貼出 經(jīng)過(guò)以上步驟就頂部導(dǎo)航切換了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容