如何在Android中为TabLayout设置自定义字体?
问题描述:
我想在我的应用程序中使用TabLayout
和ViewPager
,但我想为TabLayout
设置自定义字体,但我不能这样做!
我用这个代码:如何在Android中为TabLayout设置自定义字体?
Typeface droidSerifMonoTF = Typeface.createFromAsset(getAssets(), "fonts/DroidSerif.ttf");
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
TextView t = new TextView(this);
t.setText(mSectionsPagerAdapter.getPageTitle(i));
t.setTypeface(droidSansMonoTF);
actionBar.addTab(actionBar.newTab()
.setCustomView(t)
.setTabListener(this));
}
从这个链接:Link但不工作我!
我该怎么办?
答
您可以通过扩展TabLayout类来实现。覆盖onLayout方法波纹管:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom){
super.onLayout(changed, left, top, right, bottom);
final ViewGroup tabStrip = (ViewGroup)getChildAt(0);
final int tabCount = tabStrip.getChildCount();
ViewGroup tabView;
int tabChildCount;
View tabViewChild;
for(int i=0; i<tabCount; i++){
tabView = (ViewGroup)tabStrip.getChildAt(i);
tabChildCount = tabView.getChildCount();
for(int j=0; j<tabChildCount; j++){
tabViewChild = tabView.getChildAt(j);
if(tabViewChild instanceof AppCompatTextView){
if(fontFace == null){
fontFace = Typeface.createFromAsset(context.getAssets(), context.getString(R.string.IranSans));
}
((TextView) tabViewChild).setTypeface(fontFace, Typeface.BOLD);
}
}
}
}
必须覆盖onLayout的方法,因为,当您使用setupWithViewPager方法绑定与ViewPager的TabLayout,你必须设置标签的文本或者与的setText方法,或在PagerAdapter之后,当发生这种情况时,onLayout方法调用父ViewGroup(TabLayout),这是放置设置fontface的地方。(更改TextView文本导致调用它的父级的onLayout方法 - tabView有两个孩子,一个是ImageView另一个是TextView)
任何错误即将到来或字体不适用? –
您可以使用setCustomView()并在布局xml中为TextView定义字体,请参见:http://stackoverflow.com/questions/31698756/remove-line-break-in-tablayout –
@DanielNugent,tnx我亲爱的朋友