为Android片段设置自定义字体

21

我一直在使用Jake Wharton的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()方法。
我很难确定字体是否是问题所在,或者我尝试设置字体的位置是否有问题。

customfont.ttf 是否在 assets/fonts/ 目录下? - Kevin Coppock
@kcoppock 正确的,我已经把它放在 assets/fonts 目录下了。 - Nick
3个回答

60
你可以尝试这个。
@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
这个可行。另外,onCreateView必须返回一个视图,而你的代码没有。return v;应该放在底部。 - Nick
我的应用程序因某些原因出现了FC :/ - Si8

0
在你的ViewHolder类中定义字体。
Typeface customFontBold= Typeface.createFromAsset(getActivity().getAssets(),"fonts/JosefinSans-Bold.ttf");

像这样。


-1
我的简单代码是将在 fragment 中调用的 "context" 方法更改为 "getContext();"。//在片段中 getContext 和 getActivity 是否相同?
**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;

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