【问题标题】:Setting the context of a textview array设置 textview 数组的上下文
【发布时间】:2017-03-29 15:47:07
【问题描述】:

如何将上下文应用到 textview 数组?

TextView[] textView = new TextView[3];

for (int cell = 0; cell < 3; cell++){
    textView[cell].setText("-");
}

显然,这个错误被抛出:

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“void android.widget.TextView.setText(java.lang.CharSequence)”

如果这不是 textview array,则在调用构造函数时将活动 context 添加为 parameter 将使对象不为 null,解决我的问题:

for (int cell = 0; cell < 3; cell++){
    TextView textView = new TextView(context);
    textView.setText("-");
}

在哪里,context = getActivity().getApplicationContext()

如何为 textview 数组设置上下文参数?我想要的是每个文本视图的动态变量名称,因此我可以分别调用各个文本视图。

【问题讨论】:

    标签: java android arrays android-activity android-context


    【解决方案1】:

    你应该在调用方法之前创建对象。 试试这个:

    TextView[] textView = new TextView[3];
    
    for (int cell = 0; cell < 3; cell++) {
        textView[cell] = new TextView(context);
        textView[cell].setText("-");
    }
    

    【讨论】:

    • 好了。实例化另一个文本视图看起来是多余的。显然这是一个子对象和一个不同的方法实例。
    • 创建数组时,不会创建该数组的对象。您应该在之后创建它们
    【解决方案2】:

    我希望下面的代码可以帮助您了解视图数组的上下文。首先,您将只创建数组,但在使用它之前,您必须使用 new 关键字创建对象。

    LinearLayout rootview = (LinearLayout) findViewById(R.id.rootview);
    
    ArrayList<String> words= new ArrayList<>();     
    
    words.add("One"); words.add("two"); words.add("three"); words.add("four"); words.add("five"); words.add("six"); words.add("seven"); words.add("eight"); words.add("nine"); words.add("ten");
    
        int index=0;
        while(index<words.size()){
    
            TextView [] textViews = new TextView[words.size()];
            textViews[index] = new TextView(this);
    
            textViews[index].setText(words.get(index));
            rootview.addView(textViews[index]);
            index++;
        }
    

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 2021-10-08
      相关资源
      最近更新 更多