src中的 MainActivity :
public class MainActivity extends Activity {
/**
* 显示时间的控件
*/
private TextView tvTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
tvTime = (TextView) findViewById(R.id.tv_time);
// 开启线程,长时间循环显示时间
InnerThread thread = new InnerThread();
thread.start();
}
/**
* 循环显示时间的线程类
*/
private class InnerThread extends Thread {
@Override
public void run() {
// 循环显示时间
final Date date = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
for (int i = 0; i < 100; i++) {
date.setTime(System.currentTimeMillis());
// 显示时间
runOnUiThread(new Runnable() {
@Override
public void run() {
tvTime.setText(sdf.format(date));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
layout中的 activity_main.xml:
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv_time"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>