android学习----ProgressBar 进度条

进度条是一种非常实用的组件,下面我们来学习一下如何实用进度条


 android提供了几个进度条的样式:

   

  • Widget.ProgressBar.Horizontal
  • Widget.ProgressBar.Small
  • Widget.ProgressBar.Large
  • Widget.ProgressBar.Inverse
  • Widget.ProgressBar.Small.Inverse
  • Widget.ProgressBar.Large.Inverse
android学习----ProgressBar 进度条_第1张图片


ProgressBar组件的特有xml属性:

android学习----ProgressBar 进度条_第2张图片


下面通过案例来学习ProgressBar

(1)编写布局文件  activity_main.xml


    
    
   
    


(2)编写MainActivity.java

     由于要更新主线程UI,因此需要定义Handler来更新主线程

package com.example.progressbar;

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

public class MainActivity extends Activity {
	
	private ProgressBar progressBar = null;  //定义ProgressBar
	private TextView textView = null; //定义TextView
	private static final int PROGRESS = 0x1;
	private int mProgressStatus =20; //当前进度
	
	private Handler mHandler = new Handler();  //定义Handler,用于更新主线程UI
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//获取布局组件
		this.progressBar = (ProgressBar) findViewById(R.id.progress1); 
		this.textView = (TextView) findViewById(R.id.proText);
		
		//开启线程
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				 while (mProgressStatus < 100) {
                     mProgressStatus = doWork();

                     //更新进度条和进度内容
                     mHandler.post(new Runnable() {
                         public void run() {
                        	 progressBar.setProgress(mProgressStatus);
                        	 textView.setText("当前进度:"+mProgressStatus+"%");
                         }
                     });
                 }

			}
		}).start();
	}
	
	private int doWork(){
		mProgressStatus = mProgressStatus+1;
		try{
			Thread.sleep(100);
		}catch(Exception e){
			e.printStackTrace();
		}
		return mProgressStatus;
	}

	@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;
	}

}

运行后,效果如下:

android学习----ProgressBar 进度条_第3张图片

你可能感兴趣的:(Android)