热门IT资讯网

Android 进度条

发表于:2024-11-26 作者:热门IT资讯网编辑
编辑最后更新 2024年11月26日,package com.malakana.dialog;import android.os.Bundle;import android.os.Handler;import android.os.Mes




package com.malakana.dialog;


import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.app.Dialog;

import android.app.ProgressDialog;


public class MainActivity extends Activity {


final int PROGRESS_DIALOG = 0;

final int INCREASE = 0;

ProgressDialog pd;

Handler hd;


@SuppressLint("HandlerLeak")

@Override

public void onCreate(Bundle savedInstanceState) {

//protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);


Button bok = (Button) findViewById(R.id.button);

bok.setOnClickListener(new OnClickListener() {

@SuppressWarnings("deprecation")

@Override

public void onClick(View arg0) {

// TODO Auto-generated method stub

showDialog(PROGRESS_DIALOG); //显示对话框

}


});


// 创建Handler

hd = new Handler() {

@Override

//重写的方法

public void handleMessage(Message msg) {

//public void handlerMessage(Message msg) {

//调用父类

super.handleMessage(msg);

//判断接收的信息

switch (msg.what) {

//接收到的消息为INCREASE

case INCREASE:

//进度条每次加1

pd.incrementProgressBy(1);

//判断是否大于100

if (pd.getProgress() >= 100) {

pd.dismiss();

}

//退出

break;

}

}


};

}


//创建对话框

@Override

public Dialog onCreateDialog(int id) {

//判断id

switch (id) {

case PROGRESS_DIALOG:

pd = new ProgressDialog(this);

//设置最大值

pd.setMax(100);

pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

//设置标题

pd.setTitle(R.string.title);

pd.setCancelable(true);

//设置进度对话框不能用回退按钮关闭

//pd.setCancelable(false);

Log.d("kkk", "kkk");

break;

}

return pd;

}


@SuppressWarnings("deprecation")

@Override

//每次弹出对话框时被回调以动态更新对话框内容的方法

public void onPrepareDialog(int id, Dialog dialog) {

// 调用父类

super.onPrepareDialog(id, dialog);

switch (id) {

case PROGRESS_DIALOG:

//对话框进度清零

pd.incrementProgressBy(-pd.getProgress());

new Thread() {

public void run() {

while (true) {

hd.sendEmptyMessage(INCREASE);

if (pd.getProgress() >= 100) {

break;

}

try {

Thread.sleep(40);


} catch (Exception e) {

e.printStackTrace();

}

}

}

}.start();

break;

}

}

}


0