android design library提供的TabLayout的用法

yilugaofei 8年前發布 | 12K 次閱讀 Android開發 移動開發

原文出處:http://chenfuduo.me/2015/07/30/TabLayout-of-design-support-library/ 

在開發中,我們常常需要ViewPager結合Fragment一起使用,如下圖:
11

我們可以使用三方開源的PagerSlidingTabStrip去實現,或者viewpagerindicator,我一般都偏向前者。現在我們可以使用Design support library庫的TabLayout去實現了。最終的效果圖:
效果圖

效果圖

創建布局

  • <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="
    

        <!--app:tabMode="scrollable"  這個屬性我在代碼中設置了-->    <!-- tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);-->     <android.support.design.widget.TabLayout         android:id="@+id/sliding_tabs"         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="0px"         android:layout_weight="1"         android:background="@android:color/white" />

    </LinearLayout>

    在xml添加TabLayout,如同ViewPager,直接android.support.design.widget.TabLayout即可。還有其他的屬性我會在代碼中設置。</pre></td> </tr> </tbody> </table> </figure>

    創建Fragment

  • package me.chenfuduo.myfragmentdemo.fragment;

    import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;

    import me.chenfuduo.myfragmentdemo.R;

    /*   Created by Administrator on 2015/7/30.  */ public class PageFragment extends Fragment {

        public static final String ARG_PAGE = "ARG_PAGE";     private int mPage;

        public static PageFragment newInstance(int page) {         Bundle args = new Bundle();         args.putInt(ARG_PAGE, page);         PageFragment pageFragment = new PageFragment();         pageFragment.setArguments(args);         return pageFragment;     }

        @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         mPage = getArguments().getInt(ARG_PAGE);     }

        @Nullable     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         View view = inflater.inflate(R.layout.fragment_page, container, false);         TextView textView = (TextView) view;         textView.setText("Fragment #" + mPage);         return view;     }

    }</pre></td> </tr> </tbody> </table> </figure>

    其中Fragment的布局為:

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" />

     

    ViewPager的適配器

    package me.chenfuduo.myfragmentdemo.adapter;

    import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter;

    import me.chenfuduo.myfragmentdemo.fragment.PageFragment;

    /*   Created by Administrator on 2015/7/30.  */ public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {

        final int PAGE_COUNT = 3;     private String tabTitles[] = new String[]{"tab1","tab2","tab3"};     private Context context;

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

        @Override     public Fragment getItem(int position) {         return PageFragment.newInstance(position + 1);     }

        @Override     public int getCount() {         return PAGE_COUNT;     }

        @Override     public CharSequence getPageTitle(int position) {         return tabTitles[position];     } }</pre></td> </tr> </tbody> </table> </figure>

    設置TabLayout

    package me.chenfuduo.myfragmentdemo;

    import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem;

    import me.chenfuduo.myfragmentdemo.adapter.SimpleFragmentPagerAdapter;

    public class ThirdActivity extends FragmentActivity {

        private SimpleFragmentPagerAdapter pagerAdapter;

        private ViewPager viewPager;

        private TabLayout tabLayout;

        @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_third);         pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this);         viewPager = (ViewPager) findViewById(R.id.viewpager);         viewPager.setAdapter(pagerAdapter);         tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);         tabLayout.setupWithViewPager(viewPager);         tabLayout.setTabMode(TabLayout.MODE_FIXED);     } }</pre></td> </tr> </tbody> </table> </figure>

    這里提幾點我遇到的問題

    • tabLayout.setTabMode(TabLayout.MODE_FIXED);

    開始我設置的是:

    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);

     

    運行后,三個TabLayout標簽擠到一塊去了。如下:
    擠壓


    查看api,找到結果了。這個tabmode有兩個屬性值:

    • MODE_FIXED:Fixed tabs display all tabs concurrently and are best used with content that benefits from quick pivots between tabs.

    • MODE_SCROLLABLE:Scrollable tabs display a subset of tabs at any given moment, and can contain longer tab labels and a larger number of tabs.

    不做過多的解釋,MODE_SCROLLABLE適合很多tabs的情況。

    • setupWithViewPager必須在ViewPager.setAdapter()之后調用

    查看下源碼就知道了:

    public void setupWithViewPager(ViewPager viewPager) {
        PagerAdapter adapter = viewPager.getAdapter();
        if(adapter == null) {
            throw new IllegalArgumentException("ViewPager does not have a PagerAdapter set");
        } else {
            ...
        }
    }

     

    以上就是最基本的用法,是不是很簡單。哈~

    定義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">2dp</item>
        <item name="tabPaddingStart">12dp</item>
        <item name="tabPaddingEnd">12dp</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">14sp</item>
        <item name="android:textColor">?android:textColorSecondary</item>
        <item name="textAllCaps">true</item>
    </style>

     

    添加icon到tab

    當前的TabLayout沒有方法讓我們去添加icon,我們可以使用SpannableString結合ImageSpan來實現,在SimpleFragmentPagerAdapter中:

    private int[] imageResId = {
            R.drawable.ic_one,
            R.drawable.ic_two,
            R.drawable.ic_three
    };

    // ...

    @Override public CharSequence getPageTitle(int position) {     // Generate title based on item position     // return tabTitles[position];     Drawable image = context.getResources().getDrawable(imageResId[position]);     image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());     SpannableString sb = new SpannableString(" ");     ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);     sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);     return sb; }</pre></td> </tr> </tbody> </table> </figure>

     

    運行,發現沒有顯示,這是因為TabLayout創建的tab默認設置textAllCaps屬性為true,這阻止了ImageSpan被渲染出來,可以通過下面的樣式文件定義來改變:

  • <style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
          <item name="tabTextAppearance">@style/MyCustomTextAppearance</item>
    </style>

    <style name="MyCustomTextAppearance" parent="TextAppearance.Design.Tab">       <item name="textAllCaps">false</item> </style></pre></td> </tr> </tbody> </table> </figure>

     

    現在運行,效果就出來了。

    添加icon和text到tab

    @Override
    public CharSequence getPageTitle(int position) {
        // Generate title based on item position
        Drawable image = context.getResources().getDrawable(imageResId[position]);
        image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
        // Replace blank spaces with image icon
        SpannableString sb = new SpannableString("   " + tabTitles[position]);
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
        sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }

    我們看到在實例化SpannableString的時候,我在tabTitles[position]前面加了幾個空格,這些空格的位置是用來放置icon的。

    添加自定義的view到tab

    適配器中增加getTabView(...)方法:

    package me.chenfuduo.myfragmentdemo.adapter;

    import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView;

    import me.chenfuduo.myfragmentdemo.R; import me.chenfuduo.myfragmentdemo.fragment.PageFragment;

    /*   Created by Administrator on 2015/7/30.  */ public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {

        final int PAGE_COUNT = 3;     private String tabTitles[] = new String[]{"tab1", "tab2", "tab3"};     private int[] imageResId = {R.drawable.avatar_enterprise_vip,             R.drawable.avatar_grassroot,             R.drawable.avatar_vip};     private Context context;

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

        @Override     public Fragment getItem(int position) {         return PageFragment.newInstance(position + 1);     }

        @Override     public int getCount() {         return PAGE_COUNT;     }

        @Override     public CharSequence getPageTitle(int position) {         //第一次的代碼         //return tabTitles[position];         //第二次的代碼        /*          Drawable image = context.getResources().getDrawable(imageResId[position]);         image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());         SpannableString sb = new SpannableString(" " + tabTitles[position]);         ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);         sb.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);         return sb;/

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

    }</pre></td> </tr> </tbody> </table> </figure>

     

    簡單的布局:

  • <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="
    

        <ImageView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:id="@+id/imageView"         android:layout_centerVertical="true"         />

        <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_toRightOf="@id/imageView"         android:layout_centerVertical="true"         android:id="@+id/textView"         android:layout_marginLeft="3dp"         />

    </RelativeLayout></pre></td> </tr> </tbody> </table> </figure>

     

    使用:

    @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_third);
           pagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), this);
           viewPager = (ViewPager) findViewById(R.id.viewpager);
           viewPager.setAdapter(pagerAdapter);
           tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
           tabLayout.setupWithViewPager(viewPager);
           tabLayout.setTabMode(TabLayout.MODE_FIXED);
           for (int i = 0; i < tabLayout.getTabCount(); i++) {
               TabLayout.Tab tab = tabLayout.getTabAt(i);
               tab.setCustomView(pagerAdapter.getTabView(i));
           }
       }

     

    處理配置改變

    當屏幕旋轉或者配置改變的時候,我們需要保存當前的狀態。

    @Override
       public void onSaveInstanceState(Bundle outState) {
           super.onSaveInstanceState(outState);
           outState.putInt(POSITION,tabLayout.getSelectedTabPosition());
       }

       @Override    protected void onRestoreInstanceState(Bundle savedInstanceState) {        super.onRestoreInstanceState(savedInstanceState);        viewPager.setCurrentItem(savedInstanceState.getInt(POSITION));    }</pre></td> </tr> </tbody> </table> </figure>

     

    需要注意的是getSelectedTabPosition()方法是最新的design support library才有的。
    最后的效果如下:

    效果圖

     

     本文由用戶 yilugaofei 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
     轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
     本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
  • sesese色