fanleiym 2015-05-04
本次实例中我们呢将放上一个时钟组件,同时显示时间,显示的时间将由子线程传递到主线程进行更新
<AnalogClock android:id="@+id/analogClock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" /> <TextView android:id="@+id/info" android:layout_width="wrap_content" android:layout_height="wrap_content" />
Activity代码:
public class MainActivity extends Activity { private TextView info=null; private static final int set=1; private Handler myHandler=new Handler(){ public void handleMessage(android.os.Message msg){ switch(msg.what){//判断操作类型 case set: MainActivity.this.info.setText("当前时间为: "+msg.obj.toString());//设置文本操作 } } }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.info=(TextView)super.findViewById(R.id.info); new Thread(new ClockThread()).start(); } private class ClockThread implements Runnable{ @Override public void run() { while(true) { try{ Message msg=MainActivity.this.myHandler.obtainMessage(MainActivity.set ,new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date())); MainActivity.this.myHandler.sendMessage(msg); Thread.sleep(1000);//休眠一秒 }catch(Exception e){ } } } } }
实现效果如下: