android使用progressBar示图

  • 内容
  • 评论
  • 相关

主程序文件

package com.example.myprogressbar;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;

public class MainActivity extends Activity {
	static int progress;
	ProgressBar progressBar;
	int progressStatus = 0;
	Handler handler = new Handler();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		progress = 0;
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		progressBar.setMax(200);
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(progressStatus < 100){
					progressStatus = doSomeWork();
					
					handler.post(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							progressBar.setProgress(progressStatus);
						}
					});
				}
				
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						progressBar.setVisibility(View.GONE);
					}
				});
			}
			
			private int doSomeWork(){
				try{
					Thread.sleep(500);
				} catch(InterruptedException e) {
					e.printStackTrace();
				}
				return ++progress;
			}
		}).start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

布局文件

<?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 android:id="@+id/progressbar"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    style="@android:style/Widget.ProgressBar.Horizontal" />

</LinearLayout>

评论

0条评论

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注