有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java设置textview数组的上下文

如何将上下文应用于textview数组

TextView[] textView = new TextView[3];

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

显然,会抛出此错误:

爪哇。lang.NullPointerException:尝试调用虚拟方法“void”。小装置。文本视图。空对象引用上的setText(java.lang.CharSequence)“”

如果这不是文本视图数组,则在调用构造函数时将活动上下文添加为参数,将使对象不为空,从而解决了我的问题:

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

其中,context = getActivity().getApplicationContext()

如何设置textview数组的上下文参数?我想要的是每个textview的动态变量名,这样我可以分别调用各个textview


共 (2) 个答案

  1. # 1 楼答案

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

    TextView[] textView = new TextView[3];
    
    for (int cell = 0; cell < 3; cell++) {
        textView[cell] = new TextView(context);
        textView[cell].setText("-");
    }
    
  2. # 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++;
        }