Android学习笔记——ProgressBarHandler
2024-10-14 03:29:54
该工程的功能是实现点击按钮进度条按10%递增,使用的方式是Handler
以下的代码是MainActivity.java中的代码
package com.example.progressbarhandler; import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar; public class MainActivity extends Activity {
//申明变量
ProgressBar bar = null;
Button startButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//根据空间的ID得到代表控件的对象,并未按钮去设置监听器
bar = (ProgressBar)findViewById(R.id.bar);
startButton = (Button)findViewById(R.id.startButton);
startButton.setOnClickListener(new ButtonListener());
} class ButtonListener implements OnClickListener{ @Override
public void onClick(View v) {
// TODO Auto-generated method stub
bar.setVisibility(View.VISIBLE);
updateBarHandler.post(updateThread);
}
}
//使用匿名内部类来复写Handler当中的handMessage方法
Handler updateBarHandler = new Handler(){
public void handleMessage(Message msg){
bar.setProgress(msg.arg1);
//线程队列
updateBarHandler.post(updateThread);
}
};
//线程类,该类使用匿名内部类的方式进行声明
Runnable updateThread = new Runnable(){
int i = 0;
public void run(){
System.out.println("Begin Thread");
i = i + 10;
//得到一个消息对象,message类是由android操作系统提供
Message msg = updateBarHandler.obtainMessage();
//将msg对象的arg1参数的值设置为i,用arg1和arg2这两个成员传递消息
msg.arg1 = i;
try{
//设置当前显示睡眠1秒
Thread.sleep(1000);
}
catch (InterruptedException e){
e.printStackTrace();
}
//将msg对象加入到消息队列当中
updateBarHandler.sendMessage(msg);
if(i == 100){
//如果当i的值为100时,就将线程对象从handle当中移除
updateBarHandler.removeCallbacks(updateThread);
}
}
};
}
以下的代码是activity_main.xml中的代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" > <ProgressBar
android:id="@+id/bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:visibility="gone"
/> <Button
android:id="@+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="start"
/>
</LinearLayout>
最新文章
- 网页动物园2.0发布,经过几个月的努力,采用JAVA编写!
- PMP 第四章 项目整合管理
- 2016HUAS暑假集训训练2 K - Hero
- Tiny Rss简明安装与配置笔记
- ZIP等
- Linux系统排查2——CPU负载篇
- 将MyApp.exe和Autorun.lnk添加到NK里,在project.bib文件内加入
- Authentication token manipulation error for ubuntu ubuntu-16.04.1-desktop-amd64
- GLSL实现Image Filter 【转】
- 缓存(之一) 使用Apache Httpd实现http缓存
- 【BZOJ 1010】 [HNOI2008]玩具装箱toy (斜率优化)
- ab apache Benchmarking中链接的写法 记得加上/
- jQuery 基本实现功能模板
- HTML5简介、视频
- Android PorterDuff.Mode
- Linux 修改时区 不用重启
- 使用java API操作hdfs--读取hdfs文件并打印
- DevOps教程
- 前端JS 与 后台C# 之间JSON序列化与反序列化(笔记)
- 基于Django rest framework 和Vue实现简单的在线教育平台