Access assets in Fragment

一个人想着一个人 提交于 2019-12-02 05:15:58

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

}

i think you should use from below code:

Typeface myFont = Typeface.createFromAsset(getActivity().getAssets(), "myFont.ttf");
mTextView.setTypeface(myFont)

it worked successfully.

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