zoukankan      html  css  js  c++  java
  • Android更新UI多线程示例—五秒倒计时

    Android UI 中提供invalidate()来更新界面,而invalidate()方法是非线程安全,所以需要借助handler实现。

    main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sv2"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#48000000" >
    <TextView
    android:id="@+id/number"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="360px"
    android:textColor="#ffffff"
    android:gravity="center"
    android:paddingTop="180px" />
    </LinearLayout>
    </ScrollView>

    Test.java:

    package com.ucrobotics.test;
     
    import android.app.Activity;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.os.Handler;
    import android.view.WindowManager;
    import android.widget.ScrollView;
    import android.widget.TextView;
     
    public class Test extends Activity {
    private ScrollView sv2;
    private TextView number;
     
    private CountThread countThread = null;
    private Handler handler=null;
    private int Count_Num = 5;
     
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
     
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
     
    try {
    number = (TextView) findViewById(R.id.number);
     
    sv2 = (ScrollView) findViewById(R.id.sv2);
    sv2.setFillViewport(true); //让子元素填充
     
    sv2.setBackgroundColor(Color.GREEN);
     
    handler = new Handler();
    countThread = new CountThread();
    countThread.start();
     
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
     
     
    private class CountThread extends Thread{
    public void run()
    {
    while(Count_Num > 0) {
    handler.post(runnableUi);
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    }
     
    // 构建Runnable对象,在runnable中更新界面
    Runnable runnableUi = new Runnable(){
    @Override
    public void run() {
    number.setText(Count_Num+"");
    Count_Num--;
    }
    };
    }

    通过示例可以看出,Layout的更新请求需要通过:handler.post(runnableUi) 发送过去。
    运行效果就是启动后,屏幕数字从5倒计时到1...

  • 相关阅读:
    常用电子元器件及应用
    局域网传输-LED灯搭建局域网:数据传输可达每秒3Gb
    硬件设计原理图Checklist 参考案例二 【转载】
    基于LiFi可见光通信技术的研究及应用转化调查
    T&F 圆桌:儿童智能玩具离我们还有多远?
    一座金矿:数千亿规模智能玩具市场
    【Java】+ 图片与base64互转 + 字符串与base64互转
    【Java】+ 【wss】 + WebSocketClient
    【IDEA】+SVN
    【杂项】+事件管理之时间4象限
  • 原文地址:https://www.cnblogs.com/wzc0066/p/2948268.html
Copyright © 2011-2022 走看看