【问题标题】:Accessing static object from custom View class in Android从 Android 中的自定义 View 类访问静态对象
【发布时间】: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


【解决方案1】:

IntroScreen 的构造函数在onCreate() 被调用之前被调用,所以你的数组还没有被初始化。只需确保在膨胀您的活动之前对其进行初始化。

【讨论】:

  • 我确实在 setContentView 调用之前初始化了我的数组,但它仍然给了我 NulPointerException @DimitryBrant
  • 修复它...我的愚蠢错误。我在我的代码中调用了另一个 String[] 数组,该数组是在 setcontentview 之后初始化的。感谢您的帮助
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-12
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多