如何让我的功能不断刷新?

时间:2014-05-06 07:49:18

标签: android xml class loops layout

所以我一直在研究如何使用while方法在Java中进行循环,但它们并不适合我。我的时间功能相当简单,但它不会自行更新,因此启动时显示的时间将保持不变。

public class MainActivity extends Activity {

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

        // Time function
        TextView time = (TextView) findViewById(R.id.time);
        time.setText(DateUtils.formatDateTime(getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));

我怎样才能让我的函数重复循环,因此显示时间没有延迟。我一直在尝试很多选择,但似乎没有什么对我有用,我还在学习v,v。

谢谢,如果你帮助我的话:)。

编辑 - 我发的是什么

// Time function

final boolean keepRunning = true;
Thread thread = new Thread(){
    @Override
    public void run(){

        while(keepRunning){

            TextView time = (TextView) findViewById(R.id.time);
            time.setText(DateUtils.formatDateTime(getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));

            runOnUiThread(new Runnable(){
                @Override
                public void run(){
                    TextView time = (TextView) findViewById(R.id.time);
                    time.setText(DateUtils.formatDateTime(getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));;
                }
            });
        }
    }
};

thread.start();

3 个答案:

答案 0 :(得分:1)

在该线程内使用一个线程循环。使用runOnUiThread更新文本值(无法在工作线程中完成)。

boolean keepRunning = true;
Thread thread = new Thread(){
    @Override
    public void run(){

        while(keepRunning){

            // make the thread wait half a second (if you're only showing time up to seconds, it doesn't need to be updating constantly)
            try{
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            runOnUiThread(new Runnable(){
                @Override
                public void run(){
                    TextView time = (TextView) findViewById(R.id.time);
                    time.setText(DateUtils.formatDateTime(getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
                }
            });
        }
    }
};

thread.start();

在退出应用程序之前将keepRunning设置为false以停止该线程。

答案 1 :(得分:0)

来自developers website

new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
 }

 public void onFinish() {
     mTextField.setText("done!");
 }

}开始();

答案 2 :(得分:0)

您可以创建一个处理程序并使用它来触发此事件:

http://developer.android.com/reference/android/os/Handler.html

它有一些方法可以在将来发起一个事件:

sendMessageAtTime(Message,long)和sendMessageDelayed(Message,long)

Handler本身不能执行"重复事件",但您可以只处理Handler中的Message并通过相同的sendMessage方法重新发送新的未来事件。

相关问题