【问题标题】:How to add TextView programmatically? [duplicate]如何以编程方式添加 TextView? [复制]
【发布时间】:2019-03-13 22:03:42
【问题描述】:

我试图打印一条在文本视图中发生变化的消息。 我这样做时的问题是应用程序正在等待循环结束以放置结果。

public class Testloop extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testloop);
        String message = "test : ";
        for(int x = 1; x < 20; x = x + 1) {
             message +=x;
             int timeInMills = 1000; // time in ms
             SystemClock.sleep(timeInMills);
             TextView textView = (TextView) findViewById(R.id.txte);
             textView.setText(message);
        }
}

【问题讨论】:

    标签: java android textview


    【解决方案1】:

    onCreate 方法不是一个好地方。循环将在活动甚至可见之前完成,并且您设置的最后一个字符串将是唯一显示的字符串。尝试将 Runnable 与 Handler 一起使用,如下所示:

    private Handler handler = new Handler();
    handler.postDelayed(runnable, 100);
    

    这将告诉 runnable 在 100 毫秒内运行。然后像这样创建可运行文件:

    private Runnable runnable = new Runnable() {
       @Override
       public void run() {
          //Set your text here
          textView.setText(message);
          // here you set the runnable to run again in 100ms
          handler.postDelayed(this, 100);
       }
    };
    

    将您的消息字符串放入一个数组中,并在每次运行时通过它进行索引。

    【讨论】:

      猜你喜欢
      • 2013-04-29
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多