Android弹出进度条实例

以下是核心代码


package com.example.administrator.helloword;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;

public class ProgessDialogTest extends AppCompatActivity {
    ProgressDialog pb;
    Handler handler=new Handler(){
        public void handleMessage(Message msg){
            switch (msg.what){
                case 0x0001:
                    int index=msg.arg1;
                    pb.setProgress(index);
                    break;
                case  0x0002:
                    pb.dismiss();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initControl();
        createProgress();
    }
    public  void  dialogProgress(View view){
        pb.show();
        new Thread(){
            public void  run(){
                for(int i=0;i<=100;i++){
                    Message msg=new Message();
                    msg.what=0x0001;//注意 声明haneler的switch (msg.what) case里面有,不然不会执行
                    msg.arg1=i;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    handler.sendMessage(msg);
                }
                handler.sendEmptyMessage(0x0002);
                //注意 声明haneler的switch (msg.what) case里面有,不然不会执行
            }
        }.start();
    }

    //初始化控件
    private void initControl(){
        pb=new ProgressDialog(this);
        setContentView(R.layout.progress_dialog);
    }
    //创建进度条
    private void createProgress() {
        pb.setMessage("测试进度条");
        pb.setTitle("进度条");
        pb.setCancelable(false);//按空白地方 进度条窗口不会消失
        pb.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    }
}


评论