69

我正在使用设计支持来创建选项卡。我也ViewPager用于可滑动标签。

现在,我不知道如何只使用图标而不是选项卡中的文本。我试图找出但没有得到任何成功。

我的代码:

Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewPager = (ViewPager) findViewById(R.id.pager);
    setupViewPager(viewPager);
    setupTablayout();
}

private void setupTablayout() {
    tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setupWithViewPager(viewPager);
}

class MyPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

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

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        mFragmentTitleList.get(position)
    }
}

private void setupViewPager(ViewPager viewPager) {
    MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new frag(), "CAT");
    adapter.addFrag(new frag(), "DOG");
    adapter.addFrag(new frag(), "BIRD");
    viewPager.setAdapter(adapter);
}
4

13 回答 13

164

一种方法是在TabLayout.setupWithViewPager()方法之后设置图标。

mTabLayout.setupWithViewPager(mViewPager);
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
  mTabLayout.getTabAt(i).setIcon(R.drawable.your_icon);
}
于 2015-06-18T11:44:41.347 回答
27

以下链接中显示的教程应涵盖您想要的内容。https://github.com/codepath/android_guides/wiki/Google-Play-Style-Tabs-using-TabLayout#add-icons-to-tablayout

我复制了下面的相关部分。

将图标添加到 TabLayout

目前,TabLayout 类不提供允许选项卡中的图标的干净抽象模型。有许多已发布的解决方法,其中之一是从 PagerAdapter 的 getPageTitle(position) 方法返回 SpannableString,其中包含 ImageSpan 中的图标,如下面的代码片段所示:

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

默认情况下,由 TabLayout 创建的选项卡将 textAllCaps 属性设置为 true,从而阻止呈现 ImageSpan。您可以通过更改 tabTextAppearance 属性来覆盖此行为。

  <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>
于 2015-06-18T12:35:31.440 回答
25

在新版本中TabLayout,谷歌添加TabItem了可以通过您的 XML 使用以下代码轻松添加图标:

<android.support.design.widget.TabLayout
         app:tabTextColor="@color/gray"
         app:tabMode="fixed"
         app:tabBackground="@color/red"
         app:tabIndicatorHeight="4dp"
         app:tabIndicatorColor="@color/purple"
         app:tabPadding="2dp"
         app:tabSelectedTextColor="@color/white"
         app:tabMinWidth="64dp"
         android:layout_height="wrap_content"
         android:layout_width="match_parent">

     <!--add height and width to TabItem -->
     <android.support.design.widget.TabItem 
             android:text="@string/tab_text"/>

     <android.support.design.widget.TabItem
             android:icon="@drawable/ic_android"/>

 </android.support.design.widget.TabLayout>

在这里查看更多。

于 2016-06-01T05:46:20.763 回答
21

尝试这个

    public class GlobalActivity extends AppCompatActivity {
    Toolbar toolbar;
    ViewPager viewPager;
    TabLayout tabLayout;
    ViewPagerAdapter adapter;
    private int[] tabIcons = {
            R.drawable.home_ic,
            R.drawable.biz_ic,
            R.drawable.network_ic,
            R.drawable.offers_ic,
            R.drawable.message_ic_b
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_global_hub);
        tab();
    }
    public void tab(){
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tablayout);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();

    }
    private void setupTabIcons() {
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
        tabLayout.getTabAt(2).setIcon(tabIcons[2]);
        tabLayout.getTabAt(3).setIcon(tabIcons[3]);
        tabLayout.getTabAt(4).setIcon(tabIcons[4]);

    }
    public void setupViewPager(ViewPager viewPager){
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new GlHubFragment(),"HOME");
        adapter.addFrag(new BizForumFragment(), "BIZ FORUM");
        adapter.addFrag(new NetworkFragment(), "NETWORK");
        adapter.addFrag(new MessagesFragment(), "MESSAGEs");
        adapter.addFrag(new OfferFragmentActivity(), "OFFER");
        viewPager.setAdapter(adapter);
    }

    public class ViewPagerAdapter extends FragmentPagerAdapter{
        private final List<Fragment> mfragmentlist =new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mfragmentlist.get(position);
        }

        @Override
        public int getCount() {
            return mfragmentlist.size();
        }
        public void addFrag(Fragment fragment,String title){
            mfragmentlist.add(fragment);
            mFragmentTitleList.add(title);
        }
        @Override
        public CharSequence getPageTitle(int position){
            return mFragmentTitleList.get(position);
        }
    }
}
于 2016-05-27T13:23:34.183 回答
5

TabLayout中,设置图标很简单:

getPageTitle(position)应该返回null(如果您不想显示标题)。

下一个 :

tabLayout.getTabAt(0).setIcon(resId);

tabLayout.getTabAt(1).setIcon(resId);

......
于 2015-10-30T03:28:24.093 回答
5

当使用 TabLayout 作为 ViewPager“装饰”场景时,这些方法都不是优雅的。TabLayout 文档 这是 TabLayout 和 PagerAdapter 的一个简单扩展,它提供了一个简单的替换 TabLayout 的方法,应该能够在任一场景中使用,而无需在 TabLayout 类之外手动添加图标并遵循 PagerAdapter 的用法来获取选项卡信息.

/**
 * Created by JDL on 1/18/2017.
 */
public class TabLayoutExt extends TabLayout {

    protected ViewPager mViewPager;

    public abstract static class TabLayoutViewPagerAdapter extends PagerAdapter {
        public TabLayoutViewPagerAdapter() {
        }

        /**
         * This method may be called by the TabLayout to obtain an icon drawable
         * to for the specified tab. This method may return null
         * indicating no tab icon for this page. The default implementation returns
         * null.
         *
         * @param position The position of the title requested
         * @return A drawable icon for the requested page
         */
        public Drawable getPageIcon(Context context, int position) {
            return null;
        }
    }

    public TabLayoutExt(Context context) {
        super(context);
    }

    public TabLayoutExt(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TabLayoutExt(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        //Cover the implicit setup in TabLayout
        if (mViewPager == null) {
            final ViewParent vp = getParent();
            if (vp instanceof ViewPager) {
                mViewPager = (ViewPager)vp;
            }

        }
        super.onAttachedToWindow();
    }

    public void addTab(@NonNull Tab tab, int position, boolean setSelected) {
        if (mViewPager != null && mViewPager.getAdapter() instanceof TabLayoutViewPagerAdapter) {
            Drawable icon = ((TabLayoutViewPagerAdapter) mViewPager.getAdapter()).getPageIcon(getContext(),position);
            tab.setIcon(icon);
        }
        super.addTab(tab,position,setSelected);

    }

    @Override
    public void setupWithViewPager(@Nullable ViewPager viewPager, boolean autoRefresh) {
        mViewPager = viewPager;
        super.setupWithViewPager(viewPager, autoRefresh);
    }
}

所以所有需要做的就是扩展TabLayoutViewPagerAdapter而不是PageAdapter实现,getPageIcon(Context,int)而不是或者除了标题之外。放入TabLayoutExt您的 XML 文件,而不是普通的TabLayout. 这可以扩展为进一步修改选项卡,或者使用自定义视图或其他方式。

于 2017-01-19T18:08:55.677 回答
5

The easiest way I've found to use icons is to use Tablayout.Tab.setIcon(drawable). This also makes it easy to highlight the selected icon. If you want to do this, follow these steps.

Step 1. Add your images to the res.mipmap folders. (mipmap-mdpi, hdpi etc.) Judging by the other answers here it's also fine to put then in the res.drawable folders.

Step 2. Call setIcon on all your tabs after setting up your TabLayout and ViewPager. I did this in my AdapterTabs to keep the Activity tidy. So in your activity do this:

    tablayout = (TabLayout) findViewById(R.id.tab_layout);
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    adapterTabs = new AdapterTabs(this, getSupportFragmentManager(), fragments, tablayout, viewPager);

    viewPager.setAdapter(adapterTabs);
    tablayout.setupWithViewPager(viewPager);
    adapterTabs.setTabIcons();

and in your AdapterTabs, which should extend FragmentPagerAdapter, put your setTabIcons() method.

    public void setTabTitlesToIcons() {
    Drawable icon1 = context.getResources().getDrawable(R.mipmap.ic_1);
    Drawable icon2 = context.getResources().getDrawable(R.mipmap.ic_2);
    Drawable icon3 = context.getResources().getDrawable(R.mipmap.ic_3);
    Drawable icon1Hilighted = context.getResources().getDrawable(R.mipmap.ic_1_selected);
    Drawable icon2Hilighted = context.getResources().getDrawable(R.mipmap.ic_2_selected);
    Drawable icon3Hilighted = context.getResources().getDrawable(R.mipmap.ic_3_selected);

    icons.add(icon1);
    icons.add(icon2);
    icons.add(icon3);
    iconsHilighted.add(icon1Hilighted);
    iconsHilighted.add(icon2Hilighted);
    iconsHilighted.add(icon3Hilighted);

    for(int i = 0; i < icons.size(); i++) {
        if(i == 0) {
            //noinspection ConstantConditions
            tabLayout.getTabAt(i).setIcon(iconsSelected.get(i));
        }
        else {
            //noinspection ConstantConditions
            tabLayout.getTabAt(i).setIcon(icons.get(i));
        }
    }
}

Make sure to store a reference to the two lists 'icons' and 'iconsHilighted'. You'll need them later. Also store a reference to the TabLayout and the ViewPager which you passed in from the activity.

Step 3. Make sure AdapterTabs.getPageTitle() returns null. At this point, if you run it you should see that the first icon is highlighted.

Step 4. Implement ViewPager.OnPageChangeListener in AdapterTabs and add that listener to your viewPager

    public AdapterTabs(Context context, FragmentManager fragmentManager, List<Fragment> fragments, TabLayout tabLayout, ViewPager viewPager) {
    super(fragmentManager);
    this.context = context;
    this.tabLayout = tabLayout;
    this.viewPager = viewPager;
    this.viewPager.addOnPageChangeListener(this);

    tabs.add(fragments.get(0));
    tabs.add(fragments.get(1));
    tabs.add(fragments.get(2));
}

Step 5. Update the icons in the tabs in the onPageSelected callback in your AdapterTabs.

    @Override
public void onPageSelected(int position) {
    for (int i = 0; i < tabs.size(); i++) {
        if(i == position) {
            //noinspection ConstantConditions
            tabLayout.getTabAt(i).setIcon(iconsSelected.get(i));
        }
        else {
            //noinspection ConstantConditions
            tabLayout.getTabAt(i).setIcon(icons.get(i));
        }
    }
}

Now you should see the hilighted icon being updated when you change tabs.

于 2015-11-10T13:47:39.610 回答
3

使用材料组件库TabLayout提供的,您可以使用:

就像是:

for (int i=0;i<tabLayout.getTabCount();i++){

   tabLayout.getTabAt(i).setIcon(iconResId);
   tabLayout.getTabAt(i).
        setTabLabelVisibility(TabLayout.TAB_LABEL_VISIBILITY_UNLABELED);
}

在此处输入图像描述

于 2019-09-23T16:16:22.023 回答
2

试试这个,这肯定会奏效。

private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
        R.drawable.single,
        R.drawable.multiple};

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Choose contact");
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    tab();
}


public void tab(){
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
}

private void setupTabIcons() {
    tabLayout.getTabAt(0).setIcon(tabIcons[0]);
    tabLayout.getTabAt(1).setIcon(tabIcons[1]);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new Login());
    adapter.addFragment(new Register());
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment) {
        mFragmentList.add(fragment);

    }


}
于 2017-11-30T12:27:17.747 回答
1

正如评论中提到的,在 TabLayout 中定义图标在使用 PagerAdapter 时不起作用。对于那些使用 Kotlin 的人,一种解决方法是创建一个这样的扩展函数:

fun TabLayout.setupWithViewPagerAndKeepIcons(viewPager : ViewPager?) {
    val icons =  mutableListOf<Drawable?>()
    repeat(tabCount) {
        icons.add(getTabAt(it)?.icon)
    }
    setupWithViewPager(viewPager)

    repeat(tabCount) {
        getTabAt(it)?.setIcon(icons.get(it))
    }
}

然后在 layout.xml 中将您的图标添加到 TabLayout:

    <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout">

        <com.google.android.material.tabs.TabItem
                android:icon="@drawable/your_icon"/>

    </com.google.android.material.tabs.TabLayout>

最后,使用扩展函数来设置带有 ViewPager 的 TabLayout。

tab_layout.setupWithViewPagerAndKeepIcons(view_pager)
于 2019-08-13T11:45:00.247 回答
0

使用 ViewPager。这就是我有一个只有图标而没有文本的选项卡的方式。

TabLayout tabs...

TabLayout.Tab tab = tabs.getTabAt(0);
tab.setText("");
tab.setIcon(R.drawable.yourIcon);
于 2021-08-05T00:20:14.220 回答
0

最简单的方法是通过在 tablayout 上设置 Icon 来创建新表。下面的代码将创建两个仅带有图标的选项卡。在 onCreate() 方法上使用此代码

 tablayout = (TabLayout) findViewById(R.id.order_tablayout);
 tablayout.addTab( tablayout.newTab().setIcon(getResources().getDrawable(R.mipmap.ic_shopping_cart_white_24dp)) );
 tablayout.addTab( tablayout.newTab().setIcon(getResources().getDrawable(R.mipmap.ic_like2_fille_white_24dp)) );
于 2017-11-29T10:13:47.823 回答
-1

这可能不是所有情况的最佳答案,但我发现的还没有解决我的问题。

在查看了 Android 的实现之后,tabLayout.setupWithViewPager(ViewPager pager)我想出了一个仅使用侦听器的解决方案。

布局结构:

| LinearLayout (vertical)
|-- TabLayout (width: match_parent)
|---- TabItem (without text, just icons)
|---- TabItem
|---- ...
|-- ViewPager

两个听众的代码:

tabLayout.addOnTabSelectedListener(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) {
    }
});
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        tabLayout.setScrollPosition(position, positionOffset, false);
    }

    @Override
    public void onPageSelected(int position) {
        TabLayout.Tab tab = tabLayout.getTabAt(position);
        if (tab != null) {
            tab.select();
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
});

查看tabLayout.setScrollPosition内部调用OnPageChangeListener.onPageScrolled,了解滚动时指标或多或少的良好移动。

如果 TabLayout 的宽度未设置为 match_parent(或必须是可滚动的),这可能不起作用。

于 2017-03-03T04:05:18.103 回答