首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android自定义View类访问静态对象

Android自定义View类访问静态对象
EN

Stack Overflow用户
提问于 2017-03-13 07:47:36
回答 2查看 271关注 0票数 0

我有一个视图类IntroScreen,它在我的xml布局中被放大了。在我尝试访问在onCreate方法中定义的静态String[]元素之前,膨胀非常有效。不知何故,它给了我一个NullPointerException,即使在我初始化String[]对象之后调用膨胀我的IntroScreen视图。下面是一些代码:

代码语言:javascript
复制
//class MainActivity which holds onCreate()
static String[] stringArray;

//inside onCreate

stringArray = new String[20];
stringArray[0] = "the world";
stringArray[1] = "is round";

//a few lines down the code... still inside onCreate()
intro = (IntroScreen)this.findViewById(R.id.hereintro);

//inside my IntroScreen which extends view
//constructors are as follows:
public IntroScreen(Context c){
    super(c);
}

public IntroScreen(Context c, AttributeSet a){
 super(c, a);
 boolean b = false;

 if(MainActivity.stringArray[0].equals("the world"))b = true; //problem here
 //above line of code gives null pointer exception
} 

//inside onDraw()
//need more calls to MainActivity.stringArray in order to create custom view
//but calls won't work at all

我的问题是如何访问这个静态String[]数组?我不能将它传递给我的IntroScreen视图,因为它是通过代码行中的xml进行膨胀的

代码语言:javascript
复制
intro = (IntroScreen)this.findViewById(R.id.hereintro);  

任何建议的想法,

非常感谢

EN

回答 2

Stack Overflow用户

发布于 2017-03-13 07:52:10

IntroScreen的构造函数是在调用onCreate()之前调用的,因此您的数组尚未初始化。只需确保在膨胀活动之前将其初始化即可。

票数 1
EN

Stack Overflow用户

发布于 2017-03-13 07:53:09

将字符串数组参数传递给public IntroScreen(Context c, AttributeSet a)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42754586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档