我正在使用设计支持库来创建选项卡。默认情况下,它会创建带有文本的选项卡。如何创建只有图标的选项卡?如果它是当前选定的选项卡,我还想更改图标颜色。</p>
问问题
5037 次
4 回答
8
使用它来填充 viewPager:
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return mFragmentA;
case 1:
return mFragmentB;
case 2:
return mFragmentC;
default:
return null;
}
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
return ""; // This removes the title, as you wish
}
}
然后在 onCreateView 中:
final TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.setAdapter(new SectionPagerAdapter(getActivity().getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
也方便了解:
for (int i = 0; i < tabLayout.getTabCount(); i++) {
int iconId = -1;
switch (i) {
case 0:
iconId = R.drawable.icon1;
break;
case 1:
iconId = R.drawable.icon2;
break;
case 2:
iconId = R.drawable.icon3;
break;
}
tabLayout.getTabAt(i).setIcon(iconId);
}
// Needed since support libraries version 23.0.0
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
tabLayout.getTabAt(position).select();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
}
});
并更改选定的选项卡颜色:
tabLayout.setSelectedTabIndicatorColor(colorId); // For the line
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).getIcon().setTint(getResources().getColor(R.color.gray));
}
tabLayout.getTabAt(selectedTabPosition).getIcon().setTint(colorId);
}
于 2015-08-24T02:22:12.280 回答
2
您可以在视图寻呼机适配器中返回空标题,或者如果您需要重用适配器,只需按照设置图标的方式将标题设置为空,如下所示:
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
tab.setIcon(R.drawable.icon);
tab.setText("");
}
于 2015-08-23T10:22:50.050 回答
1
我知道没有直接的方法。但是通过文档我注意到你可以设置一个Tab
's 图标setIcon()
所以也许你做这样的事情:
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
mTabLayout.getTabAt(i).setIcon(R.drawable.icon);
}
您也可以setCustomView()
在选项卡上执行 a 。做这样的事情:
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
View v = inflater.inflate(view, parent, false);
((ImageView) v).setImageResource(R.drawable.icon);
mTabLayout.getTabAt(i).setCustomView(v);
}
于 2015-08-23T09:55:42.523 回答
1
您可以通过使用 SpannableString 并向其添加 ImageSpan 来获得“仅图标”效果。请参阅:如何在 android 中使用图像开发 PagerSlidingTabStrip?
于 2015-08-23T14:23:21.570 回答