使用TabLayout实现Google Play风格的Tabs

来源:互联网 发布:ubuntu 12.04 jdk6 编辑:程序博客网 时间:2024/05/22 10:54

使用TabLayout实现Google Play风格的Tabs

Tabs最好的实现方法就是用ViewPager和一个自定义的tab导航。这篇教程中,我们使用Google新推出的TabLayout(包含在针对Android “M”的support design library中)。

对于Android “M”以前的版本,最容易实现tabs with fragments的方式就是使用ActionBar Tabs(可以在 ActionBar Tabs with Fragments中了解)。但是,与ActionBar的导航模式有关的全部方法(例如setNavigationMode(), addTab(), selectTab())都已经不被推荐使用了。

Design Support Library

为了实现Google Play风格的Tabs,请首先确保follow了Design Support Library setup instructions。

Sliding Tabs Layout

使用android.support.design.widget.TabLayout,用来展示不同的tab选项。使用android.support.v4.view.ViewPager,用来在我们将创建的不同的fragments中翻页。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <android.support.design.widget.TabLayout        android:id="@+id/sliding_tabs"        android:layout_width="match_parent"        android:layout_height="wrap_content"        app:tabMode="scrollable" />    <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>

Create Fragment

既然已经在layout中创建了ViewPager和tabs,我们应该开始定义每个tab中的内容了。Tabs就是标示将要展示的fragment的内容,所以我们需要创建和定义将要展示的fragment。根据你自己的需要,你应该有一个或多个fragment在你的应用中。

res/layout/fragment_page.xml中定义在选中不同tab时要展示的fragment的layout:

<?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" />

PageFragment.java中定义fragment的逻辑:

// In this case, the fragment displays simple text based on the pagepublic class PageFragment extends Fragment {    public static final String ARG_PAGE = "ARG_PAGE";    private int mPage;    //newInstance constructor for creating fragment with arguments    public static PageFragment newInstance(int page) {        Bundle args = new Bundle();        args.putInt(ARG_PAGE, page);        PageFragment fragment = new PageFragment();        fragment.setArguments(args);        return fragment;    }    //Store instance variables based on arguments passed    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        mPage = getArguments().getInt(ARG_PAGE);    }    //Inflate the view for the fragment based on layout XML    @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;    }}

Implement FragmentPagerAdapter

接下来就要实现ViewPager的适配器,它控制了tabs的顺序、标题和内容。最重要的两个方法是getPageTitle(int position)(用来得到每个tab的标题)和getItem(int position)(用来决定每个tab的fragment)。

public class MainActivity extends AppCompatActivity {    //...    public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {        final int PAGE_COUNT = 3;        private String tabTitles[] = new String[] { "Tab1", "Tab2", "Tab3" };        private Context context;        public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {            super(fm);            this.context = context;        }        @Override        public int getCount() {            return PAGE_COUNT;        }        @Override        public Fragment getItem(int position) {            return PageFragment.newInstance(position + 1);        }        @Override        public CharSequence getPageTitle(int position) {            // Generate title based on item position            return tabTitles[position];        }    }}

Setup Sliding Tabs

最后,我们要关联ViewPagerSampleFragmentPagerAdapter,然后配置tabs用以下两个步骤:

  • 在activity中的onCreate()方法中连接ViewPager和adapter。
  • 为了关联pager和tabs,在TabLayout中设置ViewPager
public class MainActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        // Get the ViewPager and set it's PagerAdapter so that it can display items        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);        viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),             MainActivity.this));        // Give the TabLayout the ViewPager        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);        tabLayout.setupWithViewPager(viewPager);    }}

下面是运行示例:
运行示例

Styling the TabLayout

通常,tab导航的颜色是Material Design主题的accent color。我们能在styles.xml中自定义一个style,然后将它应用到你的TabLayout:

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

将这个style应用到你的TabLayot:

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

其他的style也能配置到TabLayout:

<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>

Add Icons to TabLayout

目前,TabLayout并没有提供一个清晰的抽象模型用来在tab中增加icon。下面贴出的代码,one of which is to return a SpannableString, containing your icon in an ImageSpan, from your PagerAdapter’s getPageTitle(position) method as shown in the code snippet below:

private int[] imageResId = {        R.drawable.ic_one,        R.drawable.ic_two,        R.drawable.ic_three};// ...@Overridepublic CharSequence getPageTitle(int position) {    // Generate title based on item position    // return tabTitles[position];    // getDrawable(int i) is deprecated, use getDrawable(int i, Theme theme) for min SDK >=21    // or ContextCompat.getDrawable(Context context, int id) if you want support for older versions.    // Drawable image = context.getResources().getDrawable(iconIds[position], context.getTheme());    // Drawable image = context.getResources().getDrawable(imageResId[position]);    Drawable image = ContextCompat.getDrawable(context, 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;}

默认情况下,由TabLayout创建的tab设置textAllCaps 属性为true,我们能通过改变tabTextAppearance属性将textAllCaps设为false。

<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>

下面是运行示例:
运行示例

Add Icons+Text to TabLayout

我们使用SpannableStringTabLayout中加入了icon,通过SpannableString在icon旁加上text也很容易。

@Overridepublic 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;}

空白空间用来放image icon,这样真正的title就能展示完全。你能在setSpan()中设定span的range start…end,这决定了你想放icon的位置。

下面是运行示例:
运行示例

0 0