Add Icons to SlidingTabLayout instead of Text

后端 未结 11 2027
执笔经年
执笔经年 2020-12-02 23:57

I\'m implementing a SlidingTabLayout in my android application. What my query is that I\'d like to implement icons in my Sliding Tabs instead of texts for navigation. I sear

11条回答
  •  误落风尘
    2020-12-03 00:28

    The key to this is to return a SpannableString, containing your icon in an ImageSpan, from your PagerAdapter's getPageTitle(position) method:

    private int[] imageResId = {
            R.drawable.ic_tab_notifications,
            R.drawable.ic_tab_weather,
            R.drawable.ic_tab_calendar
    };
    
    @Override
    public CharSequence getPageTitle(int position) {
        Drawable image = 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;
    }
    

    Normally this be would be enough, but the default tab created by SlidingTabLayout makes a call to TextView#setAllCaps(true) which effectively disables all ImageSpans, so you'll have to use a custom tab view instead:

    res/layout/custom_tab.xml

    
    
    

    and where ever you setup/bind to your ViewPager:

    SlidingTabLayout slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
    slidingTabLayout.setCustomTabView(R.layout.custom_tab, 0);
    slidingTabLayout.setViewPager(viewPager);
    

    (make sure to call setCustomTabView before setViewPager)

提交回复
热议问题