时钟及时更新演示消息传递机制(10)
本次实例中我们呢将放上一个时钟组件,同时显示时间,显示的时间将由子线程传递到主线程进行更新
- 布局函数代码:
<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){ } } } } }
实现效果如下:
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28