本文主要是介绍Handler类的简单使用与进度条的更新,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Handler类的简单使用与进度条的更新
我们废话少说直接上代码:
下面是activity_main_xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="horizontal" ><ProgressBar
android:id="@+id/progress"style="?android:attr/progressBarStyleHorizontal"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_below="@+id/textView1"android:layout_marginTop="72dp" /><TextView
android:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginTop="38dp"android:text="进度条测试"android:textSize="20sp" /></RelativeLayout>
下面是Handler类消息处理机制
Handler handler=new Handler(){@Overridepublic void handleMessage(Message msg){super.handleMessage(msg);switch (msg.what) {case INC:bar.incrementProgressBy(5);Log.d("TAGGAG", "Thread id "+Thread.currentThread().getId()+",handler INC");break;case DEC:bar.incrementProgressBy(-5);Log.d("TAGGAG", "Thread id "+Thread.currentThread().getId()+",handler DEC");break;default:Log.d("TAGGAG", "Thread id "+Thread.currentThread().getId()+",handler default");break;}}};
接下来我们来是进度条的实现,写在onStart()里
@Overrideprotected void onStart(){super.onStart();bar=(ProgressBar)findViewById(R.id.progress);bar.setProgress(0);Thread handlerBarThread=new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubfor(int i=0;i<20&&is_running;i++){try {Thread.sleep(1000);Message msg=new Message();msg.what=INC;handler.sendMessage(msg);Log.d("TAGGAG", "Thread id "+Thread.currentThread().getId()+",sendMessage INC");} catch (Exception e) {// TODO: handle exception}}for(int j=0;j<20&&is_running;j++){try {Thread.sleep(1000);Message msg=new Message();msg.what=DEC;handler.sendMessage(msg);Log.d("TAGGAG", "Thread id "+Thread.currentThread().getId()+",sendMessage DEC");} catch (Exception e) {// TODO: handle exception}}}});is_running=true;handlerBarThread.start();}
好了,运行下程序如下:
这篇关于Handler类的简单使用与进度条的更新的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!