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



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

0
1
2
.
.
.
9
10

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

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.
    }
}
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());
  }
}

试试这个:

TextView textView = (TextView) findViewById(R.id.textView);
String text = "";
for(int i=0;i<=10;i++) {
    text += String.valueOf(i) + "n"
}

textView.setText(text);

您不断覆盖 TextView 的 text 属性,每个 for 循环迭代。 相反,请执行如下操作:

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

最新更新