天天看點

Android學習之TabLayout和ViewPager

TabLayout是屬于容器空間,提供水準顯示Tab的效果,常常和ViewPager配合使用。

展示:

Android學習之TabLayout和ViewPager

添加依賴

兩種方式添加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>

public classMainActivityextendsAppCompatActivity{

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;

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

        mTabLayout.addTab(mTabLayout.newTab().setText("首頁"));
        mTabLayout.addTab(mTabLayout.newTab().setText("分類"));
        mTabLayout.addTab(mTabLayout.newTab().setText("設定"));
    }
}
           

第二種:

完全通過布局建立:

<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="首頁"
        />

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="分類"
        />

    <android.support.design.widget.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="設定"
        />

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

TabLayout屬性

顯示模式

可滑動

app:tabMode=”scrollable”

固定

app:tabMode=”fixed”

訓示器選項

app:tabIndicatorHeight=”10dp” //訓示器高度

app:tabIndicatorColor=”@color/colorPrimary” // 訓示器顔色

文字選項

app:tabSelectedTextColor=”#ffffff” // 選擇的Tab的文字顔色

app:tabTextColor=”#000000” // 未選擇的Tab文字顔色

app:tabTextAppearance=”@style/Base.TextAppearance.AppCompat.Large” // 文字樣式

背景設定

兩者沒什麼差別

android:background=”@color/colorAccent” // 背景

app:tabBackground=”@color/colorPrimary” //背景

标簽距離

app:tabPaddingStart=”10dp”

app:tabPaddingBottom=”10dp”

app:tabPadding=”10dp”

app:tabPaddingEnd=”10dp”

app:tabPaddingTop=”10dp”

對齊方式

居中顯示

app:tabGravity=”center”

填充

app:tabGravity=”fill”

偏移

從左邊開始偏移距離, 必須是可滑動的模式 scrollable

app:tabContentStart=”200dp”

Android學習之TabLayout和ViewPager

标簽寬度限制

最大寬度

app:tabMaxWidth=”50dp”

最小寬度

app:tabMinWidth=”100dp”

TabLayout提供的方法

标簽

建立标簽

TabLayout.TabnewTab()

添加标簽, 隻有添加後才能顯示

voidaddTab(TabLayout.Tab tab)

void addTab (TabLayout.Tab tab,

int position)

void addTab (TabLayout.Tab tab,

boolean setSelected)

void addTab (TabLayout.Tab tab,

int position,

boolean setSelected)

删除标簽

voidremoveTab(TabLayout.Tab tab)

通過索引删除标簽

voidremoveTabAt(intposition)

删除全部标簽

voidremoveAllTabs()

得到标簽

TabLayout.TabgetTabAt(intindex)

得到标簽總數

intgetTabCount()

設定樣式

訓示器

voidsetSelectedTabIndicatorColor(intcolor)// 訓示器顔色

void setSelectedTabIndicatorHeight (intheight) // 訓示器高度

标簽文本

voidsetTabTextColors(intnormalColor, // 正常顔色

int selectedColor) // 選擇狀态顔色

void setTabTextColors (ColorStateList textColor) // 狀态顔色

顯示模式

這個之前屬性裡面介紹過了

int getTabMode()

void setTabMode (intmode)

mode:

MODE_SCROLLABLE

MODE_FIXED

對齊方式

void setTabGravity(intgravity)

int getTabGravity ()

添加View

不止是添加标簽Tab還可以直接添加View

void addView(View child)

void addView (View child,

int index)

void addView (View child,

ViewGroup.LayoutParams params)

void addView (View child, // View對象

int index, // 位置索引

ViewGroup.LayoutParams params) // 布局參數

得到目前選擇的位置

intgetSelectedTabPosition()

監聽器

選擇監聽器

該方法已經被廢棄, 不推薦使用.

voidsetOnTabSelectedListener(TabLayout.OnTabSelectedListener listener)

替代的方法是

voidaddOnTabSelectedListener(TabLayout.OnTabSelectedListener listener)

該監聽器用完後需要删除

voidremoveOnTabSelectedListener(TabLayout.OnTabSelectedListener listener)

一次性删除所有添加的選擇監聽器

voidclearOnTabSelectedListeners()

Tab

該類時TabLayout的内部類,表示TabLayout中的每一個标簽

判斷是否被選擇

booleanisSelected()

設定為被選擇狀态

voidselect()

描述内容

如果你沒用設定描述内容, 預設的是标簽的标題

TabLayout.Tab setContentDescription(intresId)// 用strings id的

TabLayout.Tab setContentDescription (CharSequence contentDesc)

CharSequence getContentDescription ()

自定義标簽的内容

每個标簽可以盡情的自定義視圖

TabLayout.TabsetCustomView(intresId)

TabLayout.Tab setCustomView (View view)

标簽的标簽

給Tab設定tag, 然後就可以通過tag得到Tab

TabLayout.TabsetTag(Object tag)

Object getTag ()

添加圖示

TabLayout.Tab setIcon(Drawable icon)

TabLayout.Tab setIcon (intresId)

Drawable getIcon ()

标題的文字

TabLayout.TabsetText(intresId)

TabLayout.Tab setText (CharSequence text)

CharSequence getText ()

目前标簽位置

intgetPosition()

關聯ViewPager

Android學習之TabLayout和ViewPager

兩者配合使用後TabLayout就不能通過自己建立Tab,需要PagerAdapter中實作getPagerTitle()方法傳回标簽的文字。标簽的數量由ViewPager的分頁數量決定

在布局中關聯

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="vivian.com.tabandviewpager.MainActivity">

  <android.support.v4.view.ViewPager
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/viewpager"
      >
    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tab_layout"
        />

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


</LinearLayout>




public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (TabLayout)findViewById(R.id.tab_layout);
        viewPager = (ViewPager)findViewById(R.id.viewpager);


        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {

            String[] titles = new String[]{"首頁","分類","設定"};

            @Override
            public Fragment getItem(int position) {
                Log.d("position",String.valueOf(position));
                switch (position){
                    case :
                        return new Fragmentone();
                    case :
                        return new Fragmenttwo();
                    case :
                        return new Fragmentthree();
                }
                return null;
            }

            @Override
            public int getCount() {
                return ;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });



    }


}
           
Android學習之TabLayout和ViewPager

如果沒有在布局中關聯,我們就需要在ViewPager設定Adapter之後進行關聯

因為:

public void setupWithViewPager(ViewPager viewPager) {
    PagerAdapter adapter = viewPager.getAdapter();
    if(adapter == null) {
        throw new IllegalArgumentException("ViewPager does not have a PagerAdapter set");
    } else {
        ...
    }
}
           
<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

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

自定義TabLayout的樣式

預設的情況下,TabLayout的tab indicator的顔色是Material Design中的accent color(#009688),我們可以稍作修改

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabIndicatorColor">#0000FF</item>
</style>
           

然後在布局中使用

<android.support.design.widget.TabLayout
       android:id="@+id/sliding_tabs"
       style="@style/MyCustomTabLayout"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
        />
           

其他樣式參考:

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabMaxWidth">@dimen/tab_max_width</item>
    <item name="tabIndicatorColor">?attr/colorAccent</item>
    <item name="tabIndicatorHeight">dp</item>
    <item name="tabPaddingStart">dp</item>
    <item name="tabPaddingEnd">dp</item>
    <item name="tabBackground">?attr/selectableItemBackground</item>
    <item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
    <item name="tabSelectedTextColor">?android:textColorPrimary</item>
</style>
<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textSize">sp</item>
    <item name="android:textColor">?android:textColorSecondary</item>
    <item name="textAllCaps">true</item>
</style>
           

app:tabMode和app: tabGravity比較

android Material Design 中的TabLayout有兩個比較有用的屬性 app:tabMode、app:tabGravity。

(1)app:tabMode有兩個值:fixed和scrollable。

(2)app:tabGravity有兩個值:fill和center。

比較常用的是app:tabMode設定值scrollable,以及app:tabGravity設定值center。

比如,當app:tabMode設定值scrollable表示此TabLayout中當子view超出螢幕邊界時候,将提供滑動以便滑出不可見的那些子view。

而app:tabGravity設定值center,在有些情況下,比如TabLayout中子view較少需要居中顯示時候的情景。

現在給出一個例子加以說明。

1)tabGravity=”fill”和tabMode=”fixed”

Android學習之TabLayout和ViewPager

2)tabGravity=”center”和tabMode=”fixed”

Android學習之TabLayout和ViewPager

3)tabGravity=”fill”和tabMode=”scrollable”

Android學習之TabLayout和ViewPager

4)tabGravity=”cente”和tabMode=”scrollable”

Android學習之TabLayout和ViewPager

自定義view到Tab

在擴充卡中增加getTabView(。。。)方法:

class fragAdapter extends FragmentPagerAdapter{
            String[] titles = new String[]{"首頁","分類","設定"};
            private int[] images = {
                    R.mipmap.ic_launcher,
                    R.mipmap.ic_launcher,
                    R.mipmap.ic_launcher
            };

            Context context;

            public fragAdapter(FragmentManager fm, Context context) {
                super(fm);
                this.context = context;
            }

            @Override
            public Fragment getItem(int position) {
                Log.d("position",String.valueOf(position));
                switch (position){
                    case :
                        return new Fragmentone();
                    case :
                        return new Fragmenttwo();
                    case :
                        return new Fragmentthree();
                }
                return null;
            }

            @Override
            public int getCount() {
                return ;
            }

            @Override
            public CharSequence getPageTitle(int position) {
//                Drawable image = ContextCompat.getDrawable(context,images[0]);
//                image.setBounds(0,0,image.getIntrinsicWidth(),image.getIntrinsicHeight());
//                SpannableString sb = new SpannableString("   ");
//                ImageSpan imageSpan = new ImageSpan(image,ImageSpan.ALIGN_BOTTOM);
//                sb.setSpan(imageSpan,0,3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//
//                return sb;
            return null;

            }

            public View getTabView(int position){
                View view = LayoutInflater.from(context).inflate(R.layout.tabview,null);
                TextView textView = (TextView)view.findViewById(R.id.textView);
                ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
                textView.setText(titles[position]);
                imageView.setImageResource(images[position]);
                return view;
            }


        }
           

使用:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        adapter = new fragAdapter(getSupportFragmentManager(),this);

        viewPager.setAdapter(adapter) ;
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        for(int i =;i<tabLayout.getTabCount();i++){
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(adapter.getTabView(i));
        }
           

效果:

Android學習之TabLayout和ViewPager
注意:要自定義Tab,TabLayout和ViewPager不能再布局中關聯,否則顯示不出來

本篇參考于:

http://blog.csdn.net/wu371894545/article/details/65936966

http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0731/3247.html#commettop

http://blog.csdn.net/persistence_lw/article/details/70473255

後兩篇關于直接設定icon的,我實作不了,不知道原因