源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android编程实现使用handler在子线程中更新UI示例

  • 时间:2021-12-31 20:53 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android编程实现使用handler在子线程中更新UI示例
本文实例讲述了Android编程实现使用handler在子线程中更新UI。分享给大家供大家参考,具体如下: MainActivity代码:
package com.example.ui;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
  private TextView textView;
  private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
    }
  };
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView) findViewById(R.id.textView);
    new Thread(){
      @Override
      public void run() {
        super.run();
        try {
          Thread.sleep(2000);
          handler.post(new Runnable() {
            @Override
            public void run() {
             textView.setText("ok");
            }
          });
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }.start();
  }
}

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<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.ui.MainActivity">
  <TextView
    android:textSize="40sp"
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
</RelativeLayout>

更多关于Android相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/222.htm]Android线程与消息机制用法总结[/url]》、《[url=http://www.1sucai.cn/Special/410.htm]Android开发入门与进阶教程[/url]》、《[url=http://www.1sucai.cn/Special/508.htm]Android调试技巧与常见问题解决方法汇总[/url]》、《[url=http://www.1sucai.cn/Special/381.htm]Android基本组件用法总结[/url]》、《[url=http://www.1sucai.cn/Special/375.htm]Android视图View技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/371.htm]Android布局layout技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/124.htm]Android控件用法总结[/url]》 希望本文所述对大家Android程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部