大体上想实现一个思路:

对一个view 的内容进行不停地变化, 通过按钮停止这种变化,以达到随机选择的目的.


开发过程中 使用textview 模拟, 建立线程

mythread = new Thread()

{

@Override

public void run()

{

while(isrun)

{

改变textview

}

}

}

结果遭遇报错Only the original thread that created a view hierarchy can touch its views


通过在网上查阅大量资料, 得知android 的view 和相关控件不是线程安全的,不可以在线程中直接改变.


这种情况下 需要使用handle .


通过Handler更新UI实例:

步骤:

1、创建Handler对象(此处创建于主线程中便于更新UI)。

2、构建Runnable对象,在Runnable中更新界面。

3、在子线程的run方法中向UI线程post,runnable对象来更新UI。

在下面的代码中, 通过变量ab ,不断更新textview中的内容 ,通过按钮可以结束线程.


import android.os.Bundle;import android.os.Handler;import android.os.SystemClock;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.SurfaceHolder;import android.view.View;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity  {private Button button;private TextView textview;private final int SPLASH_DISPLAY_LENGHT = 1;private static int flag = 0;private static int count=0;private int ab=1;private boolean isrun = true;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);button = (Button)findViewById(R.id.button1);textview = (TextView)findViewById(R.id.textView1);final Handler handler= new Handler();       final Runnable runnable = new Runnable() {          public void run() {              textview.setText(Integer.toString(ab));          }      };                        final Thread t = new Thread(){        //public boolean isrun=true;    @Override            public void run() {              while(isrun)            {                handler.post(runnable); //加入到消息队列     这样没有启动新的线程,虽然没有报异常。但仍然阻塞ProgressDialog的显示                  ab++;                try {                    sleep(1000);                            //直接调用                  } catch (InterruptedException e) {                    return;                  }            }            }          };          t.start();          button.setOnClickListener(new Button.OnClickListener(){@Overridepublic void onClick(View view){isrun=false;}}); }             }



更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. 第10章(2)---ThreadLocal
  3. Android的Handler常见的面试问题
  4. Android(安卓)-- AppWidget 进阶篇
  5. Android(安卓)之最新最全的Intent传递数据方法
  6. android 多线程断点续传下载 二
  7. Android(安卓)中文 API (19) ―― TwoLineListItem
  8. Thread、Runable和Timer、TimerTask简述
  9. android Activity runOnUiThread() 方法使用

随机推荐

  1. 在Debian 9系统上安装Mysql数据库的方法
  2. 关于数据库连接池Druid使用说明
  3. 游戏和服备忘问题简析
  4. MySQL prepare原理详解
  5. Mysql常用sql语句汇总
  6. Centos7使用yum安装Mysql5.7.19的详细步
  7. MySQL高可用解决方案MMM(mysql多主复制管
  8. MySql Group By对多个字段进行分组的实现
  9. MySQL中的常用工具实例汇总(推荐)
  10. 详解 Mysql查询结果顺序按 in() 中ID 的