线程似乎不起作用 我试过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的一个小代码,但线程似乎不起作用 文本视图不会更改,仍会显示默认文本。
请帮助
答案 0 :(得分:3)
这里实际上有两个问题,一个是你永远不会为线程调用runnable
t = new Thread(this);
t.start();
接下来是您尝试在单独的线程中更新UI元素,而这是您无法做到的。所以在线程中你需要使用runOnUiThread()
方法来更新textview
答案 1 :(得分:2)
尝试
t = new Thread(this); // missing this
您正在从线程更新ui。
tv.setText("THis must work");
你应该从ui线程更新ui。使用runOnUiThread
将cal
和sdf
声明为类成员。
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();
}
}
}