答案 0 :(得分:7)
使用此命令填充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);
}
答案 1 :(得分:2)
您可以在视图寻呼机适配器中返回空标题,或者如果您需要重复使用适配器,只需按照设置图标的方式将标题设置为空,如下所示:
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
tab.setIcon(R.drawable.icon);
tab.setText("");
}
答案 2 :(得分:1)
我所知道的并没有直接的方法。但是通过文档我注意到你可以用Tab
设置setIcon()
的图标
所以也许你会这样做:
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
mTabLayout.getTabAt(i).setIcon(R.drawable.icon);
}
您也可以在标签上执行setCustomView()
。
做这样的事情:
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);
}
答案 3 :(得分:1)
您只能获得&#34;图标&#34;通过使用SpannableString并向其添加ImageSpan来实现效果。请参阅:How can i develop the PagerSlidingTabStrip with images in android?