*Edit
我认为它必须与Android 5.0.2做一些事情。我尝试了一个活动,它给了我同样的错误。
所以我是新的导航抽屉和片段。一切都很好,现在我想有一个textview自定义字体。通常情况下,它与下面的方法一起工作,但现在不行了。
public class HomeFragment extends Fragment {
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// I use this everytime for normal layouts, but with a fragment layout it doesnt work
TextView txt = (TextView) findViewById(R.id.textViewHome);
Typeface font = Typeface.createFromAsset(getAssets(), "impact.ttf");
txt.setTypeface(font);
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
我得到的错误是:
The method getAssets() is undefined for the type HomeFragment
The method findViewById(int) is undefined for the type HomeFragment
由于我是android编程的新手,我真的想要一个解决方案,并想了解为什么它是错误的。非常感谢所有的帮助!
您只需要更改一些东西。在获得子视图之前,您需要首先膨胀视图,并且还需要获得活动来获取资产:
public class HomeFragment extends Fragment {
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textViewHome);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "impact.ttf");
txt.setTypeface(font);
return rootView;
}
}
修改一下就行了
public class HomeFragment extends Fragment {
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView txt = (TextView) findViewById(R.id.textViewHome);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "impact.ttf");
txt.setTypeface(font);
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
这里getActivity()将给你上下文,从这个上下文你可以访问资产文件夹。它会工作的:)
尝试在字体中添加s,如assets/fonts