Set custom font for Android fragments

北城余情 提交于 2019-12-29 05:05:11

问题


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); 

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.


回答1:


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




回答2:


Define typeface in yourViewHolder class`

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

like this.




回答3:


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

**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;


来源:https://stackoverflow.com/questions/12062309/set-custom-font-for-android-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!