如何在textview中为字符串数组引入下一行?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在textview中为字符串数组引入下一行?相关的知识,希望对你有一定的参考价值。

我有字符串数组项,但每完成一个元素,我需要移动到下一行。

String[] word = { "This is text1.So it should be single line", "This is text2", "This is text3" };

broadcastMessage.setText("" + Arrays.toString(word).replaceAll("\[|\]", ""));

但是这个输出显示为,

This is text1.So it should be single line ,this is text2,this is text3.

预期输出:(应该没有逗号,应该是下一行)。

This is text1.So it should be single line
This is text2
This is text3.

但输出应该在每一行。

答案

试试这个

public class MainActivity extends AppCompatActivity {    

    String[] word = {"This is text1.So it should be single line", "This is text2", "This is text3"};

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


        TextView textView = findViewById(R.id.textureView1);
        for (int i = 0; i < word.length; i++) {
            textView.append(word[i]);
            textView.append("
");
        }



    }


}
另一答案

用这个 :

broadcastMessage.setText("
" + Arrays.toString(word).replaceAll("\[|\]", ""));
另一答案

android:singleLine = "false"在xml和broadcastMessage.setText(" " + Arrays.toString(word).replaceAll("\[|\]", ""));

另一答案

试试这样:

String abc="" + Arrays.toString(word).replaceAll("\[|\]", "");
    abc.replaceAll(",","
");
    broadcastMessage.setText(abc);
另一答案

如果您使用的是Java 8+,则可以将以下代码与lambda表达式一起使用:

String[] word = { "This is text1.So it should be single line", "This is text2", "This is text3" };
String separator = System.getProperty("line.separator");
Arrays.asList(word).forEach(w -> broadcastMessage.append(w+separator));
另一答案
public class MainActivity extends AppCompatActivity {
    String[] words = {"This is text1.So it should be single line", "This is text2", "This is text3"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
        TextView textView = findViewById(R.id.textureView);
        for (String string : words) {
            textView.setText(textView.getText().toString() + "
" + string);
        }
    }
}

以上是关于如何在textview中为字符串数组引入下一行?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 android 中为 TextView 设置字体? [复制]

如何在同一行布局 2 个 TextView(左侧 1 个,右侧 1 个)和 SeekBar

如何在 ListView 中为 TextView 的背景颜色添加渐变效果?

Android:以编程方式添加Textview,而不是将文本包装到下一行

如何在textView中为背景图像设置填充?

如何将字符串数组的元素动态插入到 textview 中并定位它?