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...

  • 相关阅读:
    elasticsearch 数据迁移
    elasticsearch使用简介 -安装篇
    docker 使用笔记
    PHP 全局变量
    做人做事需牢记20条原则
    MYSQL 存储引擎概述
    postgresql常用命令
    ORACLE 清理SYSAUX表空间
    sqlserver数据库的启动
    postgressql启动与关闭
  • 原文地址:https://www.cnblogs.com/wzc0066/p/2948268.html
Copyright © 2011-2022 走看看