TextView [] []数组是崩溃的应用程序,为什么?

时间:2014-07-05 21:28:45

标签: android arrays textview multidimensional-array

我想使用一个TextView数组。当我尝试在每个TextView数组(代码中嵌套的'for'循环)中设置每个TextView的文本时,应用程序崩溃。这是我的代码:

package com.example.whynotworking;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends Activity {

TextView[] FirstArray;
TextView[] SecondArray;
TextView[] ThirdArray;

int SizeOfTextViewArrays;

TextView[][] TheArrayArray = {FirstArray,SecondArray,ThirdArray};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.d("DebugTAG", "no problems yet");

    SizeOfTextViewArrays = 5;

    FirstArray = new TextView[SizeOfTextViewArrays];
    SecondArray = new TextView[SizeOfTextViewArrays];
    ThirdArray = new TextView[SizeOfTextViewArrays];

    Log.d("DebugTAG", "still no problems");

    taskIwantToDo();
}

public void taskIwantToDo() {
    for (int i = 0; i < TheArrayArray.length; i++) {
    for (int j = 0; j < SizeOfTextViewArrays; j++) {
        Log.d("DebugTAG", "I see this log come up once");
        TheArrayArray[i][j].setText("Text to set...");
        Log.d("DebugTAG", "But I don't see this one...");
    }
    }
}
}

我认为问题的一部分是在onCreate()方法之外声明和启动的TextView [] []数组。但是当我尝试在onCreate()中启动它时,它(eclipse IDE)告诉我“数组常量只能在初始化器中使用”......

LogCat输出为:

07-05 21:08:20.346:D / DebugTAG(340):还没有问题 07-05 21:08:20.346:D / DebugTAG(340):仍然没有问题 07-05 21:08:20.346:D / DebugTAG(340):我看到这个日志出现一次

由于

1 个答案:

答案 0 :(得分:1)

您需要创建数组的内容:

public void taskIwantToDo() {
    for (int i = 0; i < TheArrayArray.length; i++) {
        for (int j = 0; j < SizeOfTextViewArrays; j++) {
            TheArrayArray[i][j] = new TextView(this); // <-- THIS LINE
            TheArrayArray[i][j].setText("Text to set...");
        }
    }
}

之前,您需要正确创建数组。或者在模块级别完成所有工作:

int SizeOfTextViewArrays = 5;

TextView[] FirstArray = new TextView[SizeOfTextViewArrays];
TextView[] SecondArray = new TextView[SizeOfTextViewArrays];
TextView[] ThirdArray = new TextView[SizeOfTextViewArrays];

TextView[][] TheArrayArray = {FirstArray,SecondArray,ThirdArray};

或在onCreate中完成所有操作:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Log.d("DebugTAG", "no problems yet");

    SizeOfTextViewArrays = 5;

    FirstArray = new TextView[SizeOfTextViewArrays];
    SecondArray = new TextView[SizeOfTextViewArrays];
    ThirdArray = new TextView[SizeOfTextViewArrays];

    TheArrayArray = {FirstArray,SecondArray,ThirdArray};