gpt4 book ai didi

java - Activity 实例不存在 - 空对象引用

转载 作者:行者123 更新时间:2023-12-02 11:38:31 26 4
gpt4 key购买 nike

我正在尝试开发一个Android应用程序。对于我的用例,我想使用自定义字体,并且编写了一个在 View 中收集所有可用的 TextViews 的字体,以便我可以通过循环轻松设置字体。我想我应该将文本操作外包给一个名为 TextManager.class 的自己的类。但现在当我执行应用程序时,我收到错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

当我尝试在 TextMangaer.class 中设置 Typeface 时会发生这种情况。我做了一些研究,发现这是因为此时 Activity 实例不存在。但我不明白为什么,因为当我尝试在 Start.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)));

}
}

和我的TextManager.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);
}

}
}

那么我该如何解决这个问题或者我应该如何写这个?如果有人能帮我弄清楚那就太好了。提前致谢。

最佳答案

问题是获取 Assets 的上下文为空。

如果在 Activity 中使用,请使用 getContext()getApplicationContext(),但如果在 fragment 中使用,则使用 getActivity() .getContext()

Typeface font = Typeface.createFromAsset(getContext().getAssets(),  "font/ikaros_light.otf");

而不是

Typeface typeFaceIkarosLight= Typeface.createFromAsset(getAssets(), "font/ikaros_light.otf");

关于java - Activity 实例不存在 - 空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com