我想使所选选项卡的文本加粗。我应该如何通过xml或java代码实现,哪种方法更容易,请提供建议。
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getCustomView().setBackgroundDrawable(getResources().getDrawable(R.mipmap.account_active));
if (tab.getPosition()==0){
tab.getCustomView().setBackgroundDrawable(getResources().getDrawable(R.mipmap.booking_active));
}
if(tab.getPosition()==1){
tab.getCustomView().setBackgroundDrawable(getResources().getDrawable(R.mipmap.account_active));
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
if (tab.getPosition()==0){
tab.getCustomView().setBackgroundDrawable(getResources().getDrawable(R.mipmap.booking_deacive));
}
if(tab.getPosition()==1){
tab.getCustomView().setBackgroundDrawable(getResources().getDrawable(R.mipmap.account_deactive));
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
if (tab.getPosition()==0){
tab.getCustomView().setBackgroundDrawable(getResources().getDrawable(R.mipmap.booking_active));
}
if(tab.getPosition()==1){
tab.getCustomView().setBackgroundDrawable(getResources().getDrawable(R.mipmap.account_active));
}
}
});
setupTabIcons();
大家好,试试这个吧
首先添加这个方法
private void updateCounter() {
try {
for (int i = 0; i < tabLayout.getTabCount(); i++) {
updateTab(tabLayout.getTabAt(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void updateTab(TabLayout.Tab tab) {
Method method;
try {
method = TabLayout.Tab.class.getDeclaredMethod("getCustomView");
method.setAccessible(true);
View tabView = (View) method.invoke(tab, new Object[0]);
TextView tv_title = null;
if (tabView != null) {
tv_title = tabView.findViewById(R.id.tv_title);
}
switch (tab.getPosition()) {
case 0:
if (tv_title != null) {
tv_title.setText(tabTitle[0]);
if(viewPager.getCurrentItem() == 0){
tv_title.setTypeface(CustomerApplication.getInstance().getMontserratBold());
}else{
tv_title.setTypeface(CustomerApplication.getInstance().getMontserratMedium());
}
}
break;
case 1:
if (tv_title != null) {
tv_title.setText(tabTitle[1]);
if(viewPager.getCurrentItem() == 1){
tv_title.setTypeface(CustomerApplication.getInstance().getMontserratBold());
}else{
tv_title.setTypeface(CustomerApplication.getInstance().getMontserratMedium());
}
}
break;
}
tab.setCustomView(tabView);
} catch (Exception e) {
e.printStackTrace();
}
}
private final ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
updateCounter();
}
@Override
public void onPageScrollStateChanged(int state) {
}
};
@Override
public void onTabSelected(TabLayout.Tab tab) {
TextView text = (TextView) tab.getCustomView();
text.setTypeface(null, Typeface.BOLD);
text.getCustomView().measure(WRAP_CONTENT, WRAP_CONTENT)
text.getCustomView().layoutParams.height = measuredHeight
text.getCustomView().layoutParams.width = measuredWidth
}