【发布时间】:2017-03-12 23:47:35
【问题描述】:
我有一个视图类IntroScreen,它在我的 xml 布局中被夸大了。
在我尝试访问静态 String[] 元素之前,通货膨胀效果很好
在我的 onCreate 方法中定义。不知何故,它给了我一个NullPointerException,即使在我初始化我的String[] 对象之后发生了膨胀我的IntroScreen 视图的调用。这是一些代码:
//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 膨胀的
intro = (IntroScreen)this.findViewById(R.id.hereintro);
任何想法的建议,
非常感谢
【问题讨论】:
-
静态String数组的作用是什么?您的所有活动实例是否真的都一样?
-
不要像
//inside onCreate()那样写cmets,只写onCreate()的实际声明。课堂也是如此。 -
我创建了一个类(不是内部类)需要访问 MainActivity 类中定义的静态 String[] 数组。并非所有变量都是以这种方式创建的。 @代码学徒
-
对我来说,这似乎不是创建
static变量的好理由。当类的每个实例必须共享相同的值时,我只创建static变量。还有其他几种方法可以在类之间共享变量。例如,您可以将变量作为参数传递给其他类的构造函数或方法。 -
我知道我们可以做这些事情,但问题是视图是通过 xml 布局膨胀的。所以,我不能真正创建它,例如 customView = new IntroScreen(getApplicationContext(), variableToPassAsParameter)..这就是为什么我必须将它定义为静态的。 @代码学徒
标签: android arrays static android-view android-inflate