【问题标题】:Access assets in Fragment访问 Fragment 中的资产
【发布时间】:2018-12-23 18:11:13
【问题描述】:

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

Typeface custom_font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/myFont.otf");

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

我做了一些研究,发现this 问题/答案。我目前已经获得了活动上下文。


我想做的是在我的Activity 中添加以下方法:

public static Typeface getMyFont(Activity context){
    return Typeface.createFromAsset(context.getAssets(),  "fonts/myFont.otf");
}

然后像这样从我的片段中调用它:

mTextView.setTypeface(Activity.getMyFont(getActivity()));

通过执行上述操作,我没有收到任何警告,但我不确定这是否是正确的方法,所以..

我的问题是:
我应该忽略皮棉警告吗?我应该像上面那样做还是有正确的方法?

【问题讨论】:

    标签: android android-fragments android-assets android-typeface


    【解决方案1】:

    但我收到一条 lint 警告,说 getAssets() 可能返回 null。

    FragmentsgetActivity()可以返回null如果片段当前没有附加到父活动,

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

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

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

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

    【讨论】:

    • 好的,谢谢您的回答。那么,解决方法是检查 getActivity 是否为空,例如 - if (getActivity() != null)
    【解决方案2】:

    我认为你应该使用下面的代码:

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

    成功了。

    【讨论】:

    • 如果您阅读我的问题,您会发现这就是我所做的。这就是我首先提出这个问题的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-24
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2013-09-28
    • 2014-04-11
    相关资源
    最近更新 更多