How:为activity实现进度条(ProgressBar)

来源:互联网 发布:如何查看本机端口号 编辑:程序博客网 时间:2024/06/05 08:52

实现该功能的模块组成:

1.在res/layout 中对应xml布局中声明,eg:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <ProgressBar     style="@android:style/Widget.ProgressBar.Horizontal"      android:id="@+id/myProgressBar"     android:layout_width="fill_parent"     android:layout_height="wrap_content"/>    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" /></LinearLayout>
2.java代码:

    2.1.设置布局

           setContentView(R.layout.main);

    2.2.进度条实例化

          import android.widget.ProgressBar;

          private ProgressBar mProgress;

          mProgress = (ProgressBar) findViewById(R.id.myProgressBar);

    2.3.创建新进程,实现自己想要做的事情,并实现进度条动态变化,eg(比如我现在要做的事情是将我的变量mProgressStatus从依次加一,一直到一百,用进度条显示进度)

          import android.os.Handler;

          private int mProgressStatus = 0;

          private Handler mHandler = new Handler();

          new Thread(new Runnable() {
            public void run() {
                while (mProgressStatus < 100) {
                    mProgressStatus++;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    // Update the progress bar
                    mHandler.post(new Runnable() {
                        public void run() {
                            mProgress.setProgress(mProgressStatus);
                        }
                    });
                }
            }
        }).start();

原创粉丝点击