为Android片段设置自定义字体

时间:2012-08-21 20:11:11

标签: android fonts android-fragments

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

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

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

我无法弄清楚字体是否存在问题,或者我试图设置字体是不是问题。

3 个答案:

答案 0 :(得分:58)

你可以试试这个

@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;
}

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

答案 1 :(得分:0)

在yourViewHolder类中定义字体

Typeface customFontBold= Typeface.createFromAsset(getActivity().getAssets(),"fonts/JosefinSans-Bold.ttf");
像这样。

答案 2 :(得分:-1)

  

我的简单代码是更改方法调用" context"在   带有" getContext()的片段;   //片段中的getContext和getActvity是否相同?

**result**.setText("Value Expenses = " +expenses);
Typeface supercell = Typeface.createFromAsset(**getContext()**.getAssets(), "fonts/Supercell.ttf");**
**result.setTypeface(supercell);**
}catch (Exception e) 
{
Toast.makeText(getActivity(), "SUCCEED, VALUES RESULT", Toast.LENGTH_SHORT)
.show();
}
break;
相关问题