我正在尝试开发一个Android应用程序。对于我的用例,我想使用自定义字体,我编写了一个在视图中收集所有可用TextViews
的字体,以便我可以通过循环轻松设置字体。我想我应该将文本操作的东西外包给一个名为TextManager.class
的自己的类。但是现在当我执行应用程序时,我收到一个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
当我尝试在文本漫画中设置字体时,就会发生这种情况.class .我做了一些研究,发现这是因为此时活动实例不存在。但是我不明白为什么,因为当我尝试在"开始"中执行此操作时.class没有问题。
//Start.class
public class Start extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // set fullscreen
//Initialize shared preferences
prefs = getSharedPreferences("User", Context.MODE_PRIVATE);
editor=prefs.edit();
setContentView(R.layout.start_screen);
TextManager textManager= new TextManager();
textManager.setTypeface(getTextViews((ViewGroup) findViewById(R.id.root_menu)));
}
}
和我的文本管理器.class:
public class TextManager extends Start{
public TextManager(){
super();
}
public void setTypeface(List<Integer> idsOfTextViews){
Typeface typeFaceIkarosLight= Typeface.createFromAsset(getAssets(), "font/ikaros_light.otf");
for(int i=0; i < idsOfTextViews.size();i++){
((TextView)findViewById(idsOfTextViews.get(i))).setTypeface(typeFaceIkarosLight);
}
}
}
那么我该如何解决这个问题或我应该如何写这个?如果有人能帮我弄清楚,那就太好了。提前谢谢。
问题是获取资产的上下文为空。
在活动中使用getContext()
或getApplicationContext()
,但如果在片段中使用,请使用getActivity().getContext()
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "font/ikaros_light.otf");
而不是
Typeface typeFaceIkarosLight= Typeface.createFromAsset(getAssets(), "font/ikaros_light.otf");
最好制作返回字体的方法,而不是将文本视图 ID 作为参数传递。 你可以这样做:
public Typeface getTypeFace(Context context){
Typeface typeFaceIkarosLight = Typeface.createFromAsset(context.getAssets(), "font/ikaros_light.otf");
return typeFaceIkarosLight;
}
如果你想使用自定义字体,那么你可以举这个例子
本教程将向您展示如何在TextView
、EditText
和Button
上设置自定义字体。
http://androiderstack.com/index.php/2017/08/14/use-custom-font-in-textview-edittext-and-button-in-android/
这肯定会对您有所帮助