参考开源项目PagerSlidingTabStrip
做了一些小修改,比如设置Tab页平均铺满效果、字体变色等 微调的代码请 源码 下载
private void addTab(final int position, View tab) { tab.setFocusable(true); tab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pager.setCurrentItem(position); } }); tab.setPadding(tabPadding, 0, tabPadding, 0); setShouldExpand(true);//设置weight=1.0f,实现平铺的效果,add by lichen if (tab instanceof TextView) { if (position == 0) {//默认首项字体颜色,add by lichen ((TextView) tab).setTextColor(getResources().getColor(R.color.deep_green)); } else {//其他项字体颜色,add by lichen ((TextView) tab).setTextColor(getResources().getColor(R.color.light_green)); } } tabsContainer.addView(tab, position, shouldExpand ? expandedTabLayoutParams : defaultTabLayoutParams); }
@Override public void onPageSelected(int position) { View view = tabsContainer.getChildAt(position); if (view instanceof ImageButton) {//如果是图片是Tab页,add by lichen ((ImageButton) view).setImageResource(R.drawable.ic_input_add); } else if (view instanceof TextView) { setColor(position); } if (delegatePageListener != null) { delegatePageListener.onPageSelected(position); } } /** * 滑动tab修改字体颜色,by lichen * @param position */ private void setColor(int position) { TextView textView0 = (TextView) tabsContainer.getChildAt(0); TextView textView1 = (TextView) tabsContainer.getChildAt(1); TextView textView2 = (TextView) tabsContainer.getChildAt(2); switch (position) { case 0: textView0.setTextColor(getResources().getColor(R.color.deep_green)); textView1.setTextColor(getResources().getColor(R.color.light_green)); textView2.setTextColor(getResources().getColor(R.color.light_green)); break; case 1: textView0.setTextColor(getResources().getColor(R.color.light_green)); textView1.setTextColor(getResources().getColor(R.color.deep_green)); textView2.setTextColor(getResources().getColor(R.color.light_green)); break; case 2: textView0.setTextColor(getResources().getColor(R.color.light_green)); textView1.setTextColor(getResources().getColor(R.color.light_green)); textView2.setTextColor(getResources().getColor(R.color.deep_green)); break; default: break; } }
本文出自 “wIsper 把技术做成艺术” 博客,请务必保留此出处http://lichen.blog.51cto.com/697816/1414430