访问片段中的资产 [英] Access assets in Fragment

查看:112
本文介绍了访问片段中的资产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的资产文件夹中有一个字体,并且在我的片段中这样称呼它:

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

但是我收到了一个警告,说 getAssets()可能返回null。

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.

我想做的是在 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?

推荐答案


但是我收到了一个警告,说getAssets()可能返回null。

But I got a lint warning saying that getAssets() may return null.

片段 getActivity()可以返回 null

解决方案1:检查您的活动是否不为空

Solution 1 : check that your activity in not null

 if(getActivity()!=null){
            Typeface custom_font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/myFont.otf");
 }

解决方案2:,您可以使用 onAttach() 获取上下文

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

}

这篇关于访问片段中的资产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆