ANDROID_MARS学习笔记_S01原始版_007_Handler及线程的简单使用

一、运行结果

ANDROID_MARS学习笔记_S01原始版_007_Handler及线程的简单使用

一、代码
1.xml
(1)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="com.example.s01_original_e14_simplehandler.MainActivity" > <Button
android:id="@+id/startThread"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/startThread"/> <Button
android:id="@+id/stopThread"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/stopThread"
android:layout_below="@id/startThread"/> <TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/stopThread"/> </RelativeLayout>

2.java
(1)MainActivity.java

 package com.example.s01_original_e14_simplehandler;

 import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity { private Button startThread = null;
private Button stopThread = null;
private TextView myTextView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = (TextView) findViewById(R.id.myTextView);
startThread = (Button) findViewById(R.id.startThread);
stopThread = (Button) findViewById(R.id.stopThread); startThread.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handler.post(updateThread);
}
}); stopThread.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
handler.removeCallbacks(updateThread);
}
});
} Handler handler = new Handler(); Runnable updateThread = new Runnable() {
@Override
public void run() {
System.out.println("---updateThread");
myTextView.setText(System.currentTimeMillis()+"");
handler.postDelayed(updateThread, 2000);
}
}; }
上一篇:[iOS微博项目 - 2.4] - 重新安排app启动步骤


下一篇:Resharper中注释代码的快捷键