项目需要,找了很多资料终于出来了
布局
<android.support.design.widget.TabLayout android:id="@+id/tl_balance" android:layout_width="match_parent" android:layout_height="@dimen/dp71" app:paddingEnd="@dimen/dp87" app:paddingStart="@dimen/dp87" android:layout_centerInParent="true" app:tabBackground="@color/colorBiaoBg" app:tabGravity="fill" app:tabIndicatorColor="@color/colorBiaoBg" app:tabIndicatorHeight="@dimen/dp1" app:tabMode="fixed" />
代码中
balanceAdapter = new BalanceAdapter(getSupportFragmentManager(),this); vpBalance.setAdapter(balanceAdapter); vpBalance.setOffscreenPageLimit(1); //将TabLayout和ViewPager绑定在一起,使双方各自的改变都能直接影响另一方,解放了开发人员对双方变动事件的监听 tlBalance.setupWithViewPager(vpBalance); //将TabLayout和ViewPager绑定在一起,使双方各自的改变都能直接影响另一方,解放了开发人员对双方变动事件的监听 tlBalance.setupWithViewPager(vpBalance); //指定Tab的位置 //用来循环适配器中的视图总数 for (int i = 0; i < balanceAdapter.getCount(); i++) { //获取每一个tab对象 TabLayout.Tab tabAt = tlBalance.getTabAt(i); //将每一个条目设置我们自定义的视图 tabAt.setCustomView(R.layout.item_switch_text); //默认选中第一个 if (i == 0) { // 设置第一个tab的TextView是被选择的样式 tabAt.getCustomView().findViewById(R.id.tv_tab).setSelected(true);//第一个tab被选中 //设置选中标签的文字大小 ((TextView) tabAt.getCustomView().findViewById(R.id.tv_tab)).setTextSize(TypedValue.COMPLEX_UNIT_PX, 50); ((TextView) tabAt.getCustomView().findViewById(R.id.tv_tab)).setTextColor(ContextCompat.getColor(WalletActivity.this, R.color.colorFirstText)); } //通过tab对象找到自定义视图的ID TextView textView = (TextView) tabAt.getCustomView().findViewById(R.id.tv_tab); textView.setText(mTitles[i]);//设置tab上的文字 }
tlBalance.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { //在这里可以设置选中状态下 tab字体显示样式 TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab); tv.setTextSize(50); tv.setTextColor(ContextCompat.getColor(WalletActivity.this, R.color.colorFirstText)); } @Override public void onTabUnselected(TabLayout.Tab tab) { TextView tv = (TextView) tab.getCustomView().findViewById(R.id.tv_tab); tv.setTextSize(30); tv.setTextColor(ContextCompat.getColor(WalletActivity.this, R.color.colorErShiSanText)); } @Override public void onTabReselected(TabLayout.Tab tab) { } });
适配器中
public class BalanceAdapter extends FragmentPagerAdapter { private Context context; private LayoutInflater inflate; /** * tab的标题 */ private String[] mTitles = new String[]{"全部", "充值", "充电", "退费"}; public BalanceAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; inflate = LayoutInflater.from(context); } @Override public Fragment getItem(int position) { if (position == 1) { return new RechargeFragment(); } else if (position == 2) { return new ChargeBalanceFragment(); } else if (position == 3) { return new RefundFragment(); } else if (position == 0) { return new AllFragment(); } return new AllFragment(); } @Override public int getCount() { return mTitles.length; } /** * 用来设置tab的标题 */ @Override public CharSequence getPageTitle(int position) { return mTitles[position]; } }