Android之创建简单的ProgressDialog

效果图:

 

参看以下代码:

 

 

public class ProgressActivity extends Activity implements OnClickListener {
	// 最大进度
	private static final int MAX_PROGRESS = 100;
	// 进度条
	private ProgressDialog progressDialog;
	// 当前进度值
	private int progress = 0;

	// 控件
	private Button btn_progress_1;
	private Button btn_progress_2;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				if (progress > MAX_PROGRESS) {// 达到最大值
					progress = 0;
					progressDialog.dismiss();
				} else {
					progress++;
					// 进度递增1
					progressDialog.incrementProgressBy(1);
					handler.sendEmptyMessageDelayed(1,
							50 + new Random().nextInt(500));
				}
				break;

			default:
				break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_progress);
		initViews();
		initListeners();
	}

	private void initViews() {
		btn_progress_1 = (Button) findViewById(R.id.btn_progress_1);
		btn_progress_2 = (Button) findViewById(R.id.btn_progress_2);
	}

	private void initListeners() {
		btn_progress_1.setOnClickListener(this);
		btn_progress_2.setOnClickListener(this);
	}

	/**
	 * 显示对话框
	 */
	@SuppressWarnings("deprecation")
	private void showProgressDialog(int style) {
		progressDialog = new ProgressDialog(this);
		progressDialog.setIcon(R.drawable.ic_launcher);
		progressDialog.setTitle("正在处理数据...");
		progressDialog.setMessage("请稍后...");
		// 设置进度对话框的风格
		progressDialog.setProgressStyle(style);
		// 设置进度对话框的进度最大值
		progressDialog.setMax(MAX_PROGRESS);
		// 设置进度对话框的“暂停”按钮
		progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "暂停",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						handler.removeMessages(1);

					}
				});
		// 设置进度对话框的“取消”按钮
		progressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, "取消",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						handler.removeMessages(1);
						// 重置
						progress = 0;
						progressDialog.setProgress(progress);

					}
				});
		progressDialog.show();
		progress = (progress > 0) ? progress : 0;
		progressDialog.setProgress(progress);
		handler.sendEmptyMessage(1);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_progress_1:// 进度对话框
			showProgressDialog(ProgressDialog.STYLE_HORIZONTAL);
			break;
		case R.id.btn_progress_2:// 旋转对话框
			showProgressDialog(ProgressDialog.STYLE_SPINNER);
			break;
		default:
			break;
		}

	}

}

 

 

 

 

 

 

 

转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/45024997 情绪控_

©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页