-1

线程 t 似乎不起作用我试图 sysout 并签入 logcat,我试图更改 textview

package com.android.wakey;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class finallytime extends Activity implements Runnable{

    boolean n = true;
    TextView tv;
    Thread t;
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fullscreen);
        tv= (TextView) findViewById(R.id.fullscreen_content);
        System.out.println("=======>>>>>> DONE");

        t = new Thread();

        t.start();

}
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        n=false;
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        n=true;
    }

    @Override
    public void run() {
        System.out.println("====================>>>>>>>>>>>>>>>>>>>>>>\n==============================>>>>>>>>>>>>>>>>>>>>>>>" + n);
        // TODO Auto-generated method stub
        while(n){

        tv.findViewById(R.id.fullscreen_content);
        tv.setText("THis must work");
        Calendar cal = Calendar.getInstance();
        cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a");
        tv.setText((sdf.format(cal.getTime())).toString());

        try {
            t.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}
    }}

这是我为 android 构建的一个小代码,但线程似乎不起作用,文本视图没有改变,仍然显示默认文本。

请帮忙

4

2 回答 2

3

这里实际上有两个问题,一个是你从不调用线程的可运行对象

t = new Thread(this);
t.start();

接下来是您尝试在无法执行的单独线程中更新 UI 元素。所以在线程中你需要我们runOnUiThread()更新文本视图的方法

于 2013-09-20T17:10:24.963 回答
2

尝试

t = new Thread(this); // missing this

您正在从线程更新 ui。

tv.setText("THis must work");

您应该从 ui 线程更新 ui。采用runOnUiThread

宣布calsdf成为班级成员。

Calendar cal;
SimpleDateFormat sdf;

然后

@Override
public void run() {

    while(n){
    cal = Calendar.getInstance();
    cal.getTime();
    sdf = new SimpleDateFormat("HH:mm:ss a");
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            tv.setText((sdf.format(cal.getTime())).toString());
        }
    });
    try {
        t.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   }
}
于 2013-09-20T17:10:29.860 回答