Android控件之ProgressBar探究

    ProgressBar位于android.widget包下,其继承于View,主要用于显示一些操作的进度。应用程序可以修改其长度表示当前后台操作的完成情况。因为进度条会移动,所以长时间加载某些资源或者执行某些耗时的操作时,不会使用户界面失去响应。ProgressBar类的使用非常简单,只需将其显示到前台,然后启动一个后台线程定时更改表示进度的数值即可。

以下ProgressBar跟Handle结合,模拟进度条的使用,当进度条完成时会跳转到TestActivity

main.xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation
="vertical"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent">
<!-- 长方形进度条,一开始不可见,直到点击按钮时才出现进度条 -->
<ProgressBar android:id="@+id/progressBar"
style
="?android:attr/progressBarStyleHorizontal"
mce_style
="?android:attr/progressBarStyleHorizontal"
android:layout_width
="fill_parent"
android:layout_height
="wrap_content"
android:visibility
="gone"
android:max
="100" />
<!-- 圆形进度条 -->
<!--<ProgressBar android:id="@+id/progressBar"
style
="?android:attr/progressBarStyleLarge"
mce_style
="?android:attr/progressBarStyleLarge"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content" />-->
<Button android:id="@+id/start"
android:text
="启动进度条"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content" />
<Button android:id="@+id/stop"
android:text
="停止进度条"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content" />
</LinearLayout>

PbActivity类

package com.ljq.pb;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class PbActivity extends Activity {
private ProgressBar progressBar = null;
private Button start = null, stop = null;
// 定义Handler对象
private Handler handler = new Handler();


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

progressBar
= (ProgressBar) findViewById(R.id.progressBar);
progressBar.setProgress(
0);

start
= (Button) findViewById(R.id.start);
start.setOnClickListener(
new View.OnClickListener() {

public void onClick(View v) {
handler.post(runnable);
//开始执行
}

});
stop
=(Button)findViewById(R.id.stop);
stop.setOnClickListener(
new View.OnClickListener() {

public void onClick(View v) {
handler.removeCallbacks(runnable);
//停止执行
progressBar.setProgress(0);
}

});
}

int pro=0;
Runnable runnable
=new Runnable(){
public void run() {
progressBar.setVisibility(View.VISIBLE);
pro
=progressBar.getProgress()+10;
progressBar.setProgress(pro);
//如果进度小于100,,则延迟1000毫秒后重复执行runnable
if(pro<100){
handler.postDelayed(runnable,
1000);
}
else{
progressBar.setVisibility(View.GONE);
startActivity(
new Intent(PbActivity.this, TestActivity.class));
handler.removeCallbacks(runnable);
progressBar.setProgress(
0);
}
}
};
}

运行结果

  

posted on 2011-02-23 19:23  Ruthless  阅读(8326)  评论(1编辑  收藏  举报