为Android片段设置自定义字体

Nic*_*ick 20 fonts android android-fragments

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

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

onCreate主要活动中导致logcat中的空指针异常,偶尔也是如此typeface cannot be made.我也试着设置在片段本身的字体在两个onCreateonCreateView然而findViewByIdgetAssests()在片段范围知晓的方法.

我无法弄清楚字体是否是问题,或者我试图设置fn't是问题所在.

EkK*_*KoZ 59

你可以试试这个

@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;
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以在片段范围内获得上下文并获取视图和资产