I have a Font in my assets folder and I called it in my fragment like this:
Typeface custom_font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/myFont.otf");
But I got a lint warning saying that getAssets()
may return null.
I did some research and found this question/answer. I'm currently already getting the activities context.
What I was thinking of doing is adding the following method in my Activity
:
public static Typeface getMyFont(Activity context){
return Typeface.createFromAsset(context.getAssets(), "fonts/myFont.otf");
}
and then calling it from my fragment like this:
mTextView.setTypeface(Activity.getMyFont(getActivity()));
By doing the above I don't get any warnings, but I'm not sure if it is the correct way, so..
My Question is:
Should I ignore the lint warning? Should I do it like I done above or is there a correct way of doing it?
But I got a lint warning saying that getAssets() may return null.
in Fragments
getActivity()
can return null
if the fragment is not currently attached to a parent activity,
Solution 1 : check that your activity in not null
if(getActivity()!=null){
Typeface custom_font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/myFont.otf");
}
Solution 2 : you can use onAttach()
to get context
public class BlankFragment extends Fragment {
private Context mContext;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
public BlankFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Typeface custom_font = Typeface.createFromAsset(mContext.getAssets(), "fonts/myFont.otf");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
}