【问题标题】:How to set string to a random Textview in an array?如何将字符串设置为数组中的随机Textview?
【发布时间】:2019-06-09 15:33:14
【问题描述】:

我正在构建一个带有数据库的应用程序。数据库包含 Textview 的字符串。我有 6 个文本视图,其中 3 个是空的。用户使用 Edittext 插入文本,文本应与另外 3 个字符串进行比较,如果正确,则进入空文本视图。

    t1 = findViewById(R.id.textView4);
    t2 = findViewById(R.id.textView5);
    t3 = findViewById(R.id.textView6);
    t4 = findViewById(R.id.textView7);

    t5 = findViewById(R.id.textView8); //empty
    t6 = findViewById(R.id.textView9);
    t7 = findViewById(R.id.textView10); //empty
    t8 = findViewById(R.id.textView11); //empty


    a = t1.getText().toString();
    b = t2.getText().toString();
    c = t3.getText().toString();


    tL1 = new ArrayList<>();
    tL1.add(a);
    tL1.add(b);
    tL1.add(c);


    tL2 = new ArrayList<TextView>();
    if(t5.equals("")){
        tL2.add(t5);
    }
    if(t6.equals("")){
        tL2.add(t6);
    }
    if(t7.equals("")){
        tL2.add(t7);
    }
    if(t8.equals("")){
        tL2.add(t8);
    }

我使用 Arraylist 构建一个带有空文本视图的数组。现在我正在尝试用文本填充空的文本视图。如何在不知道哪个文本为空的情况下将文本放入 Textview?我试过了

tL2.get(0).setText(a);

但它不起作用。这出来了

E/AndroidRuntime: 致命异常: main. java.lang.IndexOutOfBoundsException:索引:0,大小:0

【问题讨论】:

  • 您是否知道,当您这样做时:t5.equals("") 您会将TextViewString 进行比较?
  • 我忘了...谢谢!

标签: java android arrays textview


【解决方案1】:

你得到的错误告诉你 tL2 是空的。我猜您想将 textViews 中的文本与空字符串进行比较,因此您应该将代码修改为如下所示:

if(t5.getText().equals("")){
    tL2.add(t5);
}

另外,在使用第一个元素之前,最好检查一下 tL2 里面是否有元素,所以我将最后一段代码修改为如下所示:

if (tL2.size()>0)
    tL2.get(0).setText(a);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 1970-01-01
    • 2014-02-09
    相关资源
    最近更新 更多