我目前正在尝试在fragments
之一上实现自定义字体。我尝试过使用这段代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
mRecyclerView =rootView.findViewById(R.id.recycler_view);
id = rootView.findViewById(R.id.count);
catename = rootView.findViewById(R.id.title);
Typeface sans = Typeface.createFromAsset(getActivity().getAssets(), "fonts/IRANSans.ttf");
catename.setTypeface(sans);
// other code
return rootView;
}
字体不会更改,输出仍为默认类型。我已经在主项目文件夹中创建了一个assets
文件夹,其中包含“fonts”子文件夹,其中包含文件“IRANSans.TTF”。
但它强制关闭此声明txt.setTypeface(font)
:
有谁知道解决这个问题?下面是logcat:
at android.app.ActivityThread.main(ActivityThread.java:5753)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
at aracode.ir.login.fragments.HomeFragment.onCreateView(HomeFragment.java:69)
答案 0 :(得分:0)
尝试正确地对TextView进行类型转换: -
catename =(TextView)rootView.findViewById(R.id.title);
Typeface sans = Typeface.createFromAsset(getActivity().getAssets(), "fonts/IRANSans.ttf");
catename.setTypeface(sans);
答案 1 :(得分:0)
因为它是NullPointerException
而不是类型转换错误,所以您需要检查fragment_home.xml
,并确保文本视图中包含android:id="@+id/title"