简体   繁体   中英

Add icons to Tabs in TabLayout in Android

I want to add icons to my Tabs in TabLayout in Android. I tried the Icon Array and the getTitle method. I didn't get any icons. The tabs stay with a title text only, the text in the title text array isnt used at all. Here is my code:

import statements...

public class scatter extends FragmentActivity {
    some variable declarations...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scatter);
        sensorUID = getIntent().getStringExtra("sUID");
        tankname = getIntent().getStringExtra("tNAME");
        SCALE_C = (getIntent().getStringExtra("tSCALEC"));
        SCALE_M = (getIntent().getStringExtra("tSCALEM"));
        DPs = (getIntent().getStringExtra("tDP"));
        UNITs = (getIntent().getStringExtra("tUNIT"));
        numVar = Integer.parseInt(DPs);

       final ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("Graph"));
        tabLayout.addTab(tabLayout.newTab().setText("Values"));

        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                pager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }



    private class MyPagerAdapter extends FragmentPagerAdapter {


        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int pos) {
            Fragment fragment;
            Bundle args = new Bundle();
            args.putString("senID", sensorUID);
            args.putInt("numVar", numVar);

            switch (pos) {
                case 0:
                    fragment = FirstFragment.newInstance("FirstFragment, Instance 1");
                    break;
                case 1:
                    fragment = SecondFragment.newInstance("SecondFragment, Instance 1");
                    break;
                default:
                    fragment = FirstFragment.newInstance("FirstFragment, Instance 1");
                    break;
            }
            fragment.setArguments(args);
            return fragment;
        }


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

TabLayout.Tab has a setIcon() method.

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Graph").setIcon(R.drawable.ic_graph));
    tabLayout.addTab(tabLayout.newTab().setText("Values").setIcon(R.drawable.ic_values));

as said by activesince you can use custom tab layout for this-

defining a custom style in styles.xml and then applying the style to your TabLayout:

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

You can then override this style for your TabLayout:

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

There are several other styles that can be configured for the 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>

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};
public CharSequence getPageTitle(int 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;}

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.

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

you can add icon plus text with this as follow- @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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM