如何更改PagerTitleStrip的字体

4
Typeface xyz=Typeface.createFromAsset(view.getContext().getAssets(),
                "fonts/xyz.ttf");
(TextView)abc.setTypeface(xyz);

以下是如何创建和设置自定义字体的方法。

我需要设置 pagertitlestrip 的字体,但是 pagertitlestrip 没有 .setTypeFace 函数。有人知道我怎么做吗?

3个回答

9

PagerTitleStrip实际上是扩展了ViewGroup,因此您可以只需对其进行子类化并遍历每个子项以查找需要更改字体的视图:

public class CustomFontPagerTitleStrip extends PagerTitleStrip {
    public CustomFontPagerTitleStrip(Context context) {
        super(context);
    }
    public CustomFontPagerTitleStrip(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/xyz.ttf");
        for (int i=0; i<this.getChildCount(); i++) {
            if (this.getChildAt(i) instanceof TextView) {
                ((TextView)this.getChildAt(i)).setTypeface(tf);
            }
        }
    }
}

唯一的缺点就是它会阻止Eclipse显示你的布局。

用户Gábor建议:使用if (!isInEditMode())确保它不在Eclipse中运行。 - jburns20
嗨,当我尝试将它与我的XML视图链接时,我遇到了一个类转换异常。 - Adifyr
jburns20,这是非常古老的内容,我不确定是否相关,但您可以在构造函数中始终使用isInEditMode()检查来解决“预览”问题。 - inteist

1
如果是自定义字体,请将其放入资产文件夹中,并进行如下更改。
public class WeeklyFragment extends Fragment{


PagerTitleStrip _Title;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.weekly_fragment, container, false);                   
    _Title = (PagerTitleStrip)rootView.findViewById(R.id.__Weekly_pager_title_strip);
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "your font.ttf"); 

    for (int counter = 0 ; counter<_Title.getChildCount(); counter++) {

        if (_Title.getChildAt(counter) instanceof TextView) {
            ((TextView)_Title.getChildAt(counter)).setTypeface(font);
            ((TextView)_Title.getChildAt(counter)).setTextSize(25);
        }
    }

0

虽然我认为ViewPager支持android:textAppearance,但你也不能通过这种方式设置字体。

最好的方法可能是复制PagerTitleStrip代码(在你的SDK或在线可用),将其重构为自己的包,并进行修改以适应。或者,看看ViewPagerIndicator库是否有一个你喜欢的,可以配置字体的选项。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接