<address id="ttjl9"></address>

      <noframes id="ttjl9"><address id="ttjl9"><nobr id="ttjl9"></nobr></address>
      <form id="ttjl9"></form>
        <em id="ttjl9"><span id="ttjl9"></span></em>
        <address id="ttjl9"></address>

          <noframes id="ttjl9"><form id="ttjl9"></form>

          TabLayout 全面總結

          2018-10-16    seo達人

          如果您想訂閱本博客內容,每天自動發到您的郵箱中, 請點這里

          一、簡介

          TabLayout提供了一個水平布局用于展示tabs,繼承自HorizontalScrollView。一般與Viewpager結合使用實現頁面和標簽聯動的效果,是時下APP中非常常用的一個控件



          二、基本用法

          1. 添加design依賴

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

            1
          2. xml引用
          3. xml中添加tab

            <android.support.design.widget.TabLayout

                android:id="@+id/tab_layout"

                android:layout_width="match_parent"

                android:layout_height="wrap_content">

                <android.support.design.widget.TabItem

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:text="Tab1"/>

                <android.support.design.widget.TabItem

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:text="Tab2"/>

                <android.support.design.widget.TabItem

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:text="Tab3"/>

                <android.support.design.widget.TabItem

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:text="Tab4"/>

            </android.support.design.widget.TabLayout>

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20

            21
          4. 代碼中添加tab

            <android.support.design.widget.TabLayout

                android:id="@+id/tab_layout"

                android:layout_width="match_parent"

                android:layout_height="wrap_content">

            </android.support.design.widget.TabLayout>

            1

            2

            3

            4

            5

            // tablayout,Tab是TabLayout的內部類,且Tab的構造方法是包訪問權限

            TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);

            tabLayout.addTab(tabLayout.newTab().setText("Tab1"));

            tabLayout.addTab(tabLayout.newTab().setText("Tab2"));

            tabLayout.addTab(tabLayout.newTab().setText("Tab3"));

            tabLayout.addTab(tabLayout.newTab().setText("Tab4"));

            1

            2

            3

            4

            5

            6





            三、屬性詳解

            <declare-styleable name="TabLayout">

                <!--指示器顏色-->

                <attr name="tabIndicatorColor" format="color"/>

                <!--指示器高度-->

                <attr name="tabIndicatorHeight" format="dimension"/>

                <!--tabs距TabLayout開始位置的偏移量,但app:tabMode="scrollable"才生效-->

                <attr name="tabContentStart" format="dimension"/>

                <!--僅是Tab背景,設置TabLayout背景用android:background-->

                <attr name="tabBackground" format="reference"/>

                <!--默認fixed,所有Tab只能在屏幕內顯示,超出會被擠壓;scrollable,tab數量多會超出屏幕,可滑動-->

                <attr name="tabMode">

                    <enum name="scrollable" value="0"/>

                    <enum name="fixed" value="1"/>

                </attr>

                <!--默認fill,tab填滿TabLayout,但tabMode=“fixed”才生效;center,tabs位于TabLayout的中間-->

                <attr name="tabGravity">

                    <enum name="fill" value="0"/>

                    <enum name="center" value="1"/>

                </attr>

                <!--Tab的最小寬度-->

                <attr name="tabMinWidth" format="dimension"/>

                <!--Tab的最大寬度-->

                <attr name="tabMaxWidth" format="dimension"/>

                <!--Tab文本設置樣式-->

                <attr name="tabTextAppearance" format="reference"/>

                <!--Tab未選中字體顏色-->

                <attr name="tabTextColor" format="color"/>

                <!--Tab選中字體顏色-->

                <attr name="tabSelectedTextColor" format="color"/>

                <!--Tab內填充相關-->

                <attr name="tabPaddingStart" format="dimension"/>

                <attr name="tabPaddingTop" format="dimension"/>

                <attr name="tabPaddingEnd" format="dimension"/>

                <attr name="tabPaddingBottom" format="dimension"/>

                <attr name="tabPadding" format="dimension"/>

            </declare-styleable>

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20

            21

            22

            23

            24

            25

            26

            27

            28

            29

            30

            31

            32

            33

            34

            35

            36

            使用示例



             <android.support.design.widget.TabLayout

                android:id="@+id/tab_layout"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                app:tabIndicatorColor="@color/colorPrimaryDark"

                app:tabIndicatorHeight="2dp"

                app:tabContentStart="50dp"

                app:tabBackground="@color/colorAccent"

                app:tabMode="scrollable"

                app:tabGravity="fill"

                app:tabTextAppearance="@style/MyTabTextAppearance"

                app:tabTextColor="@android:color/black"

                app:tabSelectedTextColor="@android:color/white"/>

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            <style name="MyTabTextAppearance" parent="TextAppearance.Design.Tab">

                <item name="textAllCaps">false</item>

                <item name="android:textSize">18sp</item>

            </style>

            1

            2

            3

            4





            四、圖文混排,Tab中添加圖片
          5. 通過SpannableString設置圖片

            @NonNull

            private SpannableString setImageSpan(String string,int drawableId) {

                SpannableString ss = new SpannableString("  "+string);

                Drawable drawable = ContextCompat.getDrawable(this, drawableId);

                drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());

                ImageSpan imageSpan = new ImageSpan(drawable);

                ss.setSpan(imageSpan,0,1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                return ss;

            }

            1

            2

            3

            4

            5

            6

            7

            8

            9

            TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);

            tabLayout.addTab(tabLayout.newTab().setText(setImageSpan("Tab1",R.drawable.ic_home)));

            tabLayout.addTab(tabLayout.newTab().setText(setImageSpan("Tab2",R.drawable.ic_info)));

            ……

            1

            2

            3

            4





            我們會發現個問題,通過ImageSpan設置的圖片和文字沒有對齊,先百度到一個可用方法解決:重寫ImageSpan的draw()方法



            package com.strivestay.tablayoutdemo;



            import android.graphics.Bitmap;

            import android.graphics.Canvas;

            import android.graphics.Paint;

            import android.graphics.drawable.Drawable;

            import android.support.annotation.NonNull;

            import android.text.style.ImageSpan;



            public class CenterImageSpan extends ImageSpan {

                public CenterImageSpan(Drawable drawable) {

                    super(drawable);



                }



                public CenterImageSpan(Bitmap b) {

                    super(b);

                }



                @Override

                public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom,

                                 @NonNull Paint paint) {



                    Drawable b = getDrawable();

                    Paint.FontMetricsInt fm = paint.getFontMetricsInt();

                    int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;//計算y方向的位移

                    canvas.save();

                    canvas.translate(x, transY);//繪制圖片位移一段距離

                    b.draw(canvas);

                    canvas.restore();

                }

            }

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20

            21

            22

            23

            24

            25

            26

            27

            28

            29

            30

            31

            32

            33

            將上面的ImageSpan替換為現在的CenterImageSpan,即可實現圖文混排時對齊






          6. 通過Tab.setCustomView()設置圖片
          7. 自定義view布局

            <?xml version="1.0" encoding="utf-8"?>

            <LinearLayout

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

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:orientation="vertical"

                android:gravity="center">

                <ImageView

                    android:id="@+id/iv"

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:src="@drawable/ic_home"/>

                <TextView

                    android:id="@+id/tv"

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_margin="2dp"

                    android:textSize="16sp"

                    android:text="首頁"/>

            </LinearLayout>

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20
          8. 代碼設置

             TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);

            tabLayout.addTab(tabLayout.newTab().setCustomView(setCustomView(R.drawable.ic_home,"首頁")));

            tabLayout.addTab(tabLayout.newTab().setCustomView(setCustomView(R.drawable.ic_info,"資訊")));

            tabLayout.addTab(tabLayout.newTab().setCustomView(setCustomView(R.drawable.ic_live,"直播")));

            tabLayout.addTab(tabLayout.newTab().setCustomView(setCustomView(R.drawable.ic_me,"我")));

            1

            2

            3

            4

            5

             private View setCustomView(int drawableId,String tabText) {

                View view = View.inflate(this, R.layout.item_tab, null);

                ImageView iv = (ImageView) view.findViewById(R.id.iv);

                TextView tv = (TextView) view.findViewById(R.id.tv);

                iv.setImageResource(drawableId);

                tv.setText(tabText);

                return view;

            }

            1

            2

            3

            4

            5

            6

            7

            8





            五、TabLayout與Viewpager聯動
          9. xml設置TabLayout和Viewpager

            第一種:TabLayout放置在Viewpager的上方,放在AppbarLayout中會有陰影效果



            <?xml version="1.0" encoding="utf-8"?>

            <android.support.design.widget.CoordinatorLayout

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

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

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

                android:id="@+id/main_content"

                android:layout_width="match_parent"

                android:layout_height="match_parent"

                android:fitsSystemWindows="true"

                tools:context="com.strivestay.tablayoutdemo.MainActivity">



                <android.support.design.widget.AppBarLayout

                    android:id="@+id/appbar"

                    android:layout_width="match_parent"

                    android:layout_height="wrap_content"

                    android:paddingTop="@dimen/appbar_padding_top"

                    android:theme="@style/AppTheme.AppBarOverlay">



                    <android.support.v7.widget.Toolbar

                        android:id="@+id/toolbar"

                        android:layout_width="match_parent"

                        android:layout_height="?attr/actionBarSize"

                        android:background="?attr/colorPrimary"

                        app:layout_scrollFlags="scroll|enterAlways"

                        app:popupTheme="@style/AppTheme.PopupOverlay">



                    </android.support.v7.widget.Toolbar>



                    <android.support.design.widget.TabLayout

                        android:id="@+id/tab_layout"

                        android:layout_width="match_parent"

                        android:layout_height="wrap_content"

                        app:tabIndicatorColor="@color/colorAccent"

                        app:tabIndicatorHeight="2dp"

                        app:tabBackground="@android:color/white"

                        app:tabTextAppearance="@style/MyTabTextAppearance"

                        app:tabTextColor="@android:color/black"

                        app:tabSelectedTextColor="@android:color/holo_blue_light">

                    </android.support.design.widget.TabLayout>



                </android.support.design.widget.AppBarLayout>



                <android.support.v4.view.ViewPager

                    android:id="@+id/container"

                    android:layout_width="match_parent"

                    android:layout_height="match_parent"

                    app:layout_behavior="@string/appbar_scrolling_view_behavior"/>



                <android.support.design.widget.FloatingActionButton

                    android:id="@+id/fab"

                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"

                    android:layout_gravity="end|bottom"

                    android:layout_margin="@dimen/fab_margin"

                    app:srcCompat="@android:drawable/ic_dialog_email"/>



            </android.support.design.widget.CoordinatorLayout>

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20

            21

            22

            23

            24

            25

            26

            27

            28

            29

            30

            31

            32

            33

            34

            35

            36

            37

            38

            39

            40

            41

            42

            43

            44

            45

            46

            47

            48

            49

            50

            51

            52

            53

            54

            55

            56

            57

            58





            第二種:TabLayout直接放在Viewpager,無陰影



            <android.support.v4.view.ViewPager

                android:id="@+id/container"

                android:layout_width="match_parent"

                android:layout_height="match_parent"

                app:layout_behavior="@string/appbar_scrolling_view_behavior">

                <android.support.design.widget.TabLayout

                    android:id="@+id/tab_layout"

                    android:layout_width="match_parent"

                    android:layout_height="wrap_content"

                    app:tabIndicatorColor="@color/colorAccent"

                    app:tabIndicatorHeight="2dp"

                    app:tabBackground="@android:color/white"

                    app:tabTextAppearance="@style/MyTabTextAppearance"

                    app:tabTextColor="@android:color/black"

                    app:tabSelectedTextColor="@android:color/holo_blue_light">

                </android.support.design.widget.TabLayout>

            </android.support.v4.view.ViewPager>

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17




          10. 為Viewpager創建適配器

            /

              fragment

             
            /

            public static class PlaceholderFragment extends Fragment {

                private static final String ARG_SECTION = "section";



                public PlaceholderFragment() {

                }



                public static PlaceholderFragment newInstance(String section) {

                    PlaceholderFragment fragment = new PlaceholderFragment();

                    Bundle args = new Bundle();

                    args.putString(ARG_SECTION, section);

                    fragment.setArguments(args);

                    return fragment;

                }



                @Override

                public View onCreateView(LayoutInflater inflater, ViewGroup container,

                                         Bundle savedInstanceState) {

                    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

                    TextView textView = (TextView) rootView.findViewById(R.id.section_label);

                    textView.setText(getArguments().getString(ARG_SECTION));

                    return rootView;

                }

            }



            /


              pagerAdapter

             
            /

            public class SectionsPagerAdapter extends FragmentPagerAdapter {

                String[] tabs = {"首頁","資訊","直播","我"};



                public SectionsPagerAdapter(FragmentManager fm) {

                    super(fm);

                }



                @Override

                public Fragment getItem(int position) {

                    return PlaceholderFragment.newInstance(tabs[position]);

                }



                @Override

                public int getCount() {

                    return tabs.length;

                }



                @Override

                public CharSequence getPageTitle(int position) {

                    return tabs[position];

                }

            }

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20

            21

            22

            23

            24

            25

            26

            27

            28

            29

            30

            31

            32

            33

            34

            35

            36

            37

            38

            39

            40

            41

            42

            43

            44

            45

            46

            47

            48

            49

            50

            51

            52

            主要是重寫getPageTitle()方法


          11. 代碼設置 TabLayout和Viewpager綁定

             // tablayout

            TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);



            // vp

            mViewPager = (ViewPager) findViewById(R.id.container);

            mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

            mViewPager.setAdapter(mSectionsPagerAdapter);



            // 綁定,要在viewpager設置完數據后,調用此方法,否則不顯示 tabs文本

            tabLayout.setupWithViewPager(mViewPager);

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            調用setupWithViewPager()方法,則使用TabLayout.addtab()方法無效,TabLayout會清除之前添加的所有tabs,并將根據Viewpager的頁數添加Tab,Tab標題為對應頁通過getPageTitle()返回的文本






          12. 圖文混排
          13. 同上,使用SpannableString

            修改Adapter如下:



            /*

             
            pagerAdapter

             */

            public class SectionsPagerAdapter extends FragmentPagerAdapter {



                String[] tabs = {"首頁","資訊","直播","我"};

                int[] imgs = {R.drawable.ic_home,R.drawable.ic_info,R.drawable.ic_live,R.drawable.ic_me};



                public SectionsPagerAdapter(FragmentManager fm) {

                    super(fm);

                }



                @Override

                public Fragment getItem(int position) {

                    return PlaceholderFragment.newInstance(tabs[position]);

                }



                @Override

                public int getCount() {

                    return tabs.length;

                }



                @Override

                public CharSequence getPageTitle(int position) {

            //            return tabs[position];

                    return setImageSpan(tabs[position],imgs[position]);

                }

            }

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20

            21

            22

            23

            24

            25

            26

            27

            28

            setImageSpan()方法同上






          14. 同上,使用Tab.setCustomView()

            修改pagerAdapter如下:



            /

              pagerAdapter

             
            /

            public class SectionsPagerAdapter extends FragmentPagerAdapter {



                String[] tabs = {"首頁","資訊","直播","我"};

                int[] imgs = {R.drawable.ic_home,R.drawable.ic_info,R.drawable.ic_live,R.drawable.ic_me};



                public SectionsPagerAdapter(FragmentManager fm) {

                    super(fm);

                }



                @Override

                public Fragment getItem(int position) {

                    return PlaceholderFragment.newInstance(tabs[position]);

                }



                @Override

                public int getCount() {

                    return tabs.length;

                }



                @Override

                public CharSequence getPageTitle(int position) {

            //            return tabs[position];

            //            return setImageSpan(tabs[position],imgs[position]);

                    return null;

                }



                /


                  設置自定義view

                 
            @param position

                  @return

                 
            /

                public View setCustomView(int position) {

                    View view = View.inflate(getApplicationContext(), R.layout.item_tab, null);

                    ImageView iv = (ImageView) view.findViewById(R.id.iv);

                    TextView tv = (TextView) view.findViewById(R.id.tv);

                    iv.setImageResource(imgs[position]);

                    tv.setText(tabs[position]);

                    return view;

                }

            }

            1

            2

            3

            4

            5

            6

            7

            8

            9

            10

            11

            12

            13

            14

            15

            16

            17

            18

            19

            20

            21

            22

            23

            24

            25

            26

            27

            28

            29

            30

            31

            32

            33

            34

            35

            36

            37

            38

            39

            40

            41

            42

            43

            代碼修改如下:



            …………

            // 綁定,要在viewpager設置完數據后,調用此方法,否則不顯示 tabs文本

            tabLayout.setupWithViewPager(mViewPager);



            // 為綁定viewpager后的TabLayout的tabs設置自定義view

            for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {

                tabLayout.getTabAt(i).setCustomView(mSectionsPagerAdapter.setCustomView(i));

            }

            1

            2

            3

            4

            5

            6

            7

            8

            發現問題:我使用的仍然是上面的item_tab,但是只顯示圖片,不顯示文字如下







            翻了翻源碼,也沒發現有對Tab的標題有特別的設置;后來,就感覺是不是顏色問題,給item_tab中的textview加上屬性android:textColor="@android:color/black",就顯示出來了







            六、FlycoTabLayout

            這是一個不錯的TabLayout開源項目,效果挺好,可以了解一下。





            藍藍設計www.syprn.cn )是一家專注而深入的界面設計公司,為期望卓越的國內外企業提供卓越的UI界面設計、BS界面設計 、 cs界面設計 、 ipad界面設計 、 包裝設計 、 圖標定制 、 用戶體驗 、交互設計、 網站建設 、平面設計服務

          日歷

          鏈接

          個人資料

          藍藍設計的小編 http://www.syprn.cn

          存檔

          亚洲va欧美va天堂v国产综合