为 Android 片段设置自定义字体 [英] Set custom font for Android fragments

查看:33
本文介绍了为 Android 片段设置自定义字体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Jake Wharton 的 ViewPagerIndicator,目前我正在尝试在我的一个片段上实现自定义字体.我试过使用这个代码:

I have been using Jake Wharton's ViewPagerIndicator and I am currently trying to implement a custom font on one of my fragments. I've tried using this code:

   TextView txt = (TextView) findViewById(R.id.Zipcode);
    Typeface font = Typeface.createFromAsset(getAssets(), "fonts/customfont.ttf");
    txt.setTypeface(font); 

在主要活动的onCreate中,导致logcat中出现空指针异常,偶尔字体无法制作.我还尝试在 onCreateonCreateView 中设置片段本身的字体,但是 findViewByIdgetAssests() 是片段范围内的未知方法.

In the onCreate for the main activity which results in a null pointer exception in logcat and occasionally typeface cannot be made. I've also tried to set the font in the fragment itself in both the onCreate and onCreateView however findViewById and getAssests() are unknown methods in the fragment scope.

我无法确定是字体有问题还是我尝试设置字体的位置有问题.

I'm having trouble figuring out if the font is the problem or where I am trying to set the fon't is the problem.

推荐答案

你可以试试这个

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle     savedInstanceState) {
       View v = inflater.inflate(R.layout.fragment_layout, container, false);
       TextView txt = (TextView) v.findViewById(R.id.Zipcode);
       Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/customfont.ttf");
       txt.setTypeface(font); 
       return v;
}

有了这个,您可以在片段范围内获得上下文并获取视图和资产

with this you can have the context in the scope of the fragment and get the view and the assets

这篇关于为 Android 片段设置自定义字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆