Tablayout with icons only

后端 未结 12 1385
暗喜
暗喜 2020-12-04 11:32

I am using design support to create tabs. I am also using ViewPager for swipable tabs.

Now, I don\'t know how to use only icons instead of texts in tabs

12条回答
  •  一整个雨季
    2020-12-04 11:54

    The tutorial shown in the following link should cover what you want. https://github.com/codepath/android_guides/wiki/Google-Play-Style-Tabs-using-TabLayout#add-icons-to-tablayout

    I copied the relevant section below.

    Add Icons to TabLayout

    Currently, the TabLayout class does not provide a clean abstraction model that allows for icons in your tab. There are many posted workarounds, 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
    };
    
    // ...
    
    @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;
    }
    

    By default, the tab created by TabLayout sets the textAllCaps property to be true, which prevents ImageSpans from being rendered. You can override this behavior by changing the tabTextAppearance property.

      
    
      
    

提交回复
热议问题