Android 《Tablayout》

作者: 泅渡者 | 来源:发表于2017-10-17 16:13 被阅读52次
滑动选项布局

曾经我们如果要实现选项卡样式我们会有很多种办法,大多是RadioGroup+ViewPager / TabHost+Fragment / 纯Button+Fragment替换模式。但是现在官方为我们提供了组件让我们去用,而且相对以前而言效果更好特效更多。

  • 用法(后面讲的组件将会跳过该步骤)

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

activity_tablayout.xml

<?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:tabMaxWidth="0dp"
        app:tabGravity="fill"
        app:tabMode="fixed" />

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

由于要用到ViewPager那么就少不了使用Fragment。
fragment_page.xml

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

接下来我们看看TablayoutActivity.class 和PageFragment.class:
TablayoutActivity.class

/**
 * Created by 泅渡者
 * Created on 2017/10/17.
 */

public class TablayoutActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tablayout);


        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
                this));

        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}

PageFragment.class

/**
 * Created by 泅渡者
 * Created on 2017/10/17.
 */

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 fragment = new PageFragment();
        fragment.setArguments(args);
        return fragment;
    }

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

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

我们看到SampleFragmentPagerAdapter还没有介绍,其实它是ViewPager的适配器,为ViewPager填充Fragment。
SampleFragmentPagerAdapter.class:

/**
 * Created by 泅渡者
 * Created on 2017/10/17.
 */

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) {
        return tabTitles[position];
    }
}

代码介绍完毕,那么我们看看实际的效果如何?

image.png

效果很赞的,相对而言还添加了下标,这可为我们省去很多的麻烦。
下面是Tablayout的一些属性:

属性名 Options 描述
tabBackground @drawable/image 选项卡背景
tabGravity center, fill 选项的对齐属性
tabIndicatorColor @color/blue 下表颜色
tabIndicatorHeight @dimen/tabh 下表高度
tabMaxWidth @dimen/tabmaxw 选项的最大宽度
tabMode fixed, scrollable 选项是固定还是滚动
tabTextColor @color/blue 选项卡字体颜色

自定义样式

通常我们会更改选项卡的样式,那么我们需要在styles.xml文件中添加自定义样式。

<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabIndicatorColor">#0000FF</item>
</style>
<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>

还可以为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>

这里的样式就留给大家自己去试试吧。

Tablayout 添加图标

目前,TabLayout类不提供属性,来设置标签中的图标。但是,我们可以在设置TabLayout后手动添加图标。
在FragmentPagerAdapter里面,需要删除getPageTitle()行,或者简单地返回null:
然后在TablayoutActivity.class中做如下添加

/**
 * Created by 泅渡者
 * Created on 2017/10/17.
 * @author User
 */

public class TablayoutActivity extends AppCompatActivity {

    /**
     * 添加图标
     */
    int[] imageResId = {
            R.drawable.icon_one,
            R.drawable.icon_two,
            R.drawable.icon_three };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tablayout);


        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
                this));

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

        tabLayout.setupWithViewPager(viewPager);
       
         /**
         * 添加图标
         */
        for (int i = 0; i < imageResId.length; i++) {
            tabLayout.getTabAt(i).setIcon(imageResId[i]);
        }
    }
}

image.png

图文混合选项卡

代码如下

/**
 * Created by 泅渡者
 * Created on 2017/10/17.
 */

public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 3;
    private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
    /**
     * 添加图标
     */
    private int[] imageResId = {
            R.drawable.icon_one,
            R.drawable.icon_two,
            R.drawable.icon_three};
    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) {
//        return tabTitles[position]; //纯文字标题
//        return null;//纯图片标题

        /**
         * 图文混排标题
         */
        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_BASELINE);

        sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }

}

同时需要修改Styles.xml

    <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>
image.png
上面出现了一个SpannableString,不了解的可以点进去瞅瞅。。。

自定义Tab

这里我给出官方的代码不再去代码中更改程序。
适配器中写法如下:

public class SampleFragmentPagerAdapter extends FragmentPagerAdapter {
   private String tabTitles[] = new String[] { "Tab1", "Tab2" };
   private int[] imageResId = { R.drawable.ic_one, R.drawable.ic_two };

    public View getTabView(int position) {
        // Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
        View v = LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
        TextView tv = (TextView) v.findViewById(R.id.textView);
        tv.setText(tabTitles[position]);
        ImageView img = (ImageView) v.findViewById(R.id.imgView);
        img.setImageResource(imageResId[position]);
        return v;
    }

}
    // Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        SampleFragmentPagerAdapter pagerAdapter = 
            new SampleFragmentPagerAdapter(getSupportFragmentManager(), MainActivity.this);
        viewPager.setAdapter(pagerAdapter);

        // Give the TabLayout the ViewPager
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);

        // Iterate over all tabs and set the custom view
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            tab.setCustomView(pagerAdapter.getTabView(i));
        }

状态记录

在我们之前写的Tablayout中经常会出现横竖屏切换后Tab选中状态重置的问题,这里也是一样,需要我们手动做下记录。

  public static String POSITION = "POSITION";

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

好了以上就是Tablayout 的所有,有需要的可以收藏下。。
需要代码点击获取

相关文章

网友评论

    本文标题:Android 《Tablayout》

    本文链接:https://www.haomeiwen.com/subject/dwdduxtx.html