Android应用程序生成随机单词每秒,并将其显示在屏幕上 [英] Android app that generates random words every second and displays them on screen

查看:200
本文介绍了Android应用程序生成随机单词每秒,并将其显示在屏幕上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让一个Android应用程序产生一个随机字每1秒?
这里是我的code:

How can I make an android app that generates a random word every 1 second? Here is my code:

new Timer().scheduleAtFixedRate(new TimerTask(){
            public void run()
            {
        started = true;
        word = "";
        for (int i = 0; i < lenght+1; i++)
        {
            int j = rand.nextInt((max-min) + 1) + min;
            word += tr.Translate(j);
        }
        txt.setText(word);
            }

    }, 0, 5000);

看来,我的应用程序停止每次都必须改变的TextView(TXT)的文本;我怎样才能使这项工作?

It seems that my app stops every time it must change the text of the TextView("txt"); how can I make this work?

推荐答案

Undoubtfully,一个线程中运行这个。这样做,它会产生背景的话,一旦它已经拥有,主UI线程必须追加只是内容到 TXT 实例。

Undoubtfully, run this within a Thread. Doing this, it will generate the words in background and once it already has, the main UI thread must just append the content to the txt instance.

new Thread(
  new Runnable() { 
    public void run() {
      // your stuff
    }
  }
).start()

要分配结果到 TXT 对象,你可能无法此线程内做到这一点。要做到这一点,你需要声明一个处理程序活动并使用你的线程内的处理程序,所以它采用的sendMessage()来的主要活动和活动只是设置文本。

To assign the result to the txt object, you'll probably be unable to do it within this thread. To do so, you'll need to declare a Handler in your Activity and use that handler within your thread, so it uses sendMessage() to the main Activity and the Activity just sets the text.

更多关于此这里和的这里

---- ----编辑

由于@FD_说,还有另一种方式来做到更新,而无需使用的处理程序。你只需要调用 runOnUiThread()方法是这样的:

As @FD_ says, there is another way to do the update without the use of a Handler. You would just need to call the runOnUiThread() method, something like this:

runOnUiThread(new Runnable() {
  public void run() {
    txt.setText(your_new_text);
  }
});

另一种方法是使用的AsyncTask ,这是(含糊地谈到)的线程,这使得很多东西对你的进化。更多关于的AsyncTask 取值这里

Another way is using an AsyncTask, which is (talking vaguely) an "evolution" of a thread which makes a lot of stuff for you. More on AsyncTasks here.

---- ----编辑

这将是途径之一:

new Thread(
  new Runnable() { 
    public void run() {
      new Timer().scheduleAtFixedRate(new TimerTask() {
        public void run()   {
          started = true;
          word = "";
          for (int i = 0; i < lenght+1; i++)
          {
            int j = rand.nextInt((max-min) + 1) + min;
            word += tr.Translate(j);
          }

          // This will update your txt instance without the need of a Handler
          runOnUiThread(new Runnable() {
            public void run() {
              txt.setText(word);
            }
          });
        }
      }, 0, 5000);
    }
  }).start();

这篇关于Android应用程序生成随机单词每秒,并将其显示在屏幕上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆