我尝试在Android中刷新TextView。我在我的代码中使用ExecutorService。当我按下“开始刷新”按钮时,几秒钟后我的应用程序已被Android系统停止。我在stackoverflow.com上看了几个主题,但我仍然无法理解我做错了什么。这是我的代码:
MainActivity.java:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MainActivity extends Activity {
private static ExecutorService exec;
private static TextView textView;
private static Calendar cal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text_field);
cal = new GregorianCalendar();
exec = Executors.newSingleThreadExecutor();
}
private static class Task implements Runnable {
@Override
public void run() {
try {
while(!Thread.currentThread().isInterrupted()) {
textView.setText(cal.getTime().toString());
TimeUnit.SECONDS.sleep(1);
}
}
catch (InterruptedException e) {
return;
}
}
}
public void finish_refresh(View view) {
exec.shutdownNow();
}
public void start_refresh(View view) {
exec.submit(new Task());
}
}
activity_main.xml中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button android:layout_width="200dp"
android:layout_height="50dp"
android:text="@string/start_refresh"
android:onClick="start_refresh"/>
<Button android:layout_width="200dp"
android:layout_height="50dp"
android:text="@string/finish_refresh"
android:onClick="finish_refresh"/>
<TextView android:layout_height="200dp"
android:layout_width="200dp"
android:layout_marginTop="10dp"
android:id="@+id/text_field" />
</LinearLayout>
答案 0 :(得分:1)
你需要使用runOnUiThread() 在onCreate()方法中添加以下代码:
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
// update TextView here!
textView.setText(cal.getTime().toString());
}
});
}
} catch (InterruptedException e) { }
}
};
t.start();