Android 進度條

1、activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="進度條" />

</LinearLayout>

2、MainActivity.java類的實現

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

類的實現

public class MainActivity extends Activity {
	private Button btn1;
	
	final int MAX_PROGRESS = 333;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		btn1 = (Button) findViewById(R.id.button1);
		btn1.setOnClickListener(new OnClickListener() {
			//	進度條
			ProgressDialog progress;
			//	是否取消進度
			Boolean bCancle = false;
			@Override
			public void onClick(View v) {
				progress = new ProgressDialog(MainActivity.this);
				
				progress.setIcon(R.drawable.ic_launcher);
				progress.setTitle("進度條窗口");
				progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				progress.setMax(MAX_PROGRESS);
				progress.setButton("取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						bCancle = true;
					}
				});
				progress.show();
				
				//	創建一個線程
				Thread thread = new Thread(r);
				thread.start();

			}	
			
			//	線程響應
			Runnable r = new Runnable() {
				public void run() {
					int nStep = 0;
					while (nStep < MAX_PROGRESS) {
						if (bCancle) {
							break;
						}
						
						try {
							Thread.sleep(100);
							nStep++;
							progress.incrementProgressBy(1);
							
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}				
			};
		});
	}
}

3、效果圖

效果圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章