如何在setText()方法中使用多个换行符?

时间:2016-01-20 18:29:48

标签: android

如何在setText()方法中使用多个换行符?例如,我编写了以下简单代码,我希望在单独的行中看到每个数字,如下所示:

0
1
2
.
.
.
9
10

我使用for(int i=0; i=10; i++),但当我运行以下代码作为结果时,我只看到10中的textView值。

public class MainActivity extends Activity {

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

        TextView textView = (TextView) findViewById(R.id.textView);

        for(int i=0;i<=10;i++)
         textView.setText(String.valueOf(i) + "\n"); // I see only the 10 value in the textView object.
    }
}

3 个答案:

答案 0 :(得分:2)

public class MainActivity extends Activity {

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

    TextView textView = (TextView) findViewById(R.id.textView);

    StringBuilder sb = new StringBuilder();

    for(int  i =0;i<10;i++){
        sb.append(i+"\n");  
    }
    textView.setText(sb.toString());
  }
}

答案 1 :(得分:1)

试试这个:

TextView textView = (TextView) findViewById(R.id.textView);

String text = "";

for(int i=0;i<=10;i++) {
    text += String.valueOf(i) + "\n"
}


textView.setText(text);

答案 2 :(得分:0)

每次for循环迭代都会覆盖TextView的text属性。相反,做这样的事情:

textView.setText(textView.getText().toString() + String.valueOf(i) + "\n");