android 反纠结app开发: 在线程中更新view
来源:互联网 发布:淘宝能在线订单吗 编辑:程序博客网 时间:2024/06/05 09:27
大体上想实现一个思路:
对一个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 0
- android 反纠结app开发: 在线程中更新view
- 反纠结app开发: activity之间的数据传递
- Android 开发中 app版本更新功能
- android在线程中更新TextView
- android在子线程中更新数据
- Android开发之-- 利用百度sdk实现在app中提示其更新
- Android显示系统之View与SurfaceView更新屏幕的区别.对于View.则是在UI主线程中更新画面.SurfaceView更新屏幕,是在非UI线程(主线程)中实现SurfaceHolde
- Android 怎样在其他线程中更新UI 线程
- Android 在其他线程中更新UI 线程
- android 在其他线程中更新UI线程的解决方法
- Android线程模型--在子线程中更新UI
- Android 在其他线程中更新UI线程的解决方法
- Android 在其他线程中更新UI线程的解决方法
- Android 在其他线程中更新UI线程的解决方法
- Android 开发中我常用的手机App(持续更新)
- android 开发 App下载更新
- android 线程更新view及数据传送
- android app开发之app本地更新
- 学习】poj题目推荐+50题说明
- JavaScript RegExp(正则表达式) 对象
- Magento 给用户customer ,添加一个属性
- MFC(补充)
- MongoDB 逻辑与操作
- android 反纠结app开发: 在线程中更新view
- myeclipse或者eclipse因为异常而不能部署项目
- Annotation注解的工作原理
- HTML5 input元素类型:email及url介绍_html5教程技巧
- 一种基于重载的高效c#上图片添加文字图形图片的方法
- 正则表达式
- 电脑里的文档报表丢失误删怎么恢复
- csdn排版问题
- C# Redis实战(六)