为 Android 片段设置自定义字体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12062309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:36:57  来源:igfitidea点击:

Set custom font for Android fragments

androidfontsandroid-fragments

提问by Nick

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

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

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

In the onCreatefor 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 onCreateand onCreateViewhowever findViewByIdand getAssests()are unknown methods in the fragment scope.

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

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.

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

回答by EkKoZ

You can try this

你可以试试这个

@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

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

回答by Abhi Soni

Define typeface in yourViewHolder class`

在 yourViewHolder 类中定义字体`

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

like this.

像这样。

回答by Sultand

My Simple code is change method call "context" in the fragment with "getContext(); //is getContext and getActvity same in fragment??

我的简单代码是使用“getContext();”在片段中更改方法调用“context”;//片段中的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;