5

我想尝试将字符串数组设置为 textview 的文本。我怎样才能做到这一点?

以下是我到目前为止尝试过的:

String[] word = { "Pretty", "Cool", "Weird" };

tv.setText( word.length );

但它抛出了一些错误。我是 Android/Java 新手

4

2 回答 2

22

word.length给你数组的长度,而不是内容。您的意思是将内容设置为tv. 您可以使用Arrays#toString方法: -

String[] word = { "Pretty", "Cool", "Weird" };

// Prints [Pretty, Cool, Weird]
tv.setText(Arrays.toString(word));   

// Prints Pretty, Cool, Weird
tv.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));
于 2012-10-13T13:46:16.097 回答
6

TextView.setText()将 aCharSequence作为第一个参数,因此如果intword.length.

使用增强的 for 循环:

String[] word = { "Pretty", "Cool", "Weird" };
StringBuilder builder = new StringBuilder();
for (String s: word) {
    builder.append(s);
    builder.append(" ");
}

tv.setText(builder.toString().trim()); // .trim to remove the trailing space.

或者从 Java 8 开始:

tv.setText(String.join(" ", word));
于 2012-10-13T13:49:19.567 回答