欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 进度条

程序员文章站 2024-02-03 18:58:40
...

Android 进度条

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.test12.MainActivity" >

   <Button 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Button1"
       android:onClick="btn1Onclick"/>

</RelativeLayout>
package com.example.test12;

import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {
	private final static  int Msg_PROGRESS=0x001;
	private final static  int Msg_FINISH=0x002;
	private ProgressDialog dlg;
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Msg_PROGRESS:
				int progress=msg.arg1;
				dlg.setProgress(progress);
				break;
			case Msg_FINISH:
				dlg.dismiss();
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		dlg=new ProgressDialog(this);
		dlg.setIcon(R.drawable.ic_launcher);
		dlg.setMessage("这是一个进度条");
		dlg.setTitle("进度条");
		dlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	}

	public void btn1Onclick(View view){
		dlg.show();
		new Thread(){
			@Override
			public void run() {
				for(int i=0;i<100;i++){
					Message msg=handler.obtainMessage();
					msg.what=Msg_PROGRESS;
					msg.arg1=i;
					handler.sendMessage(msg);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				handler.sendEmptyMessage(Msg_FINISH);
			}
		}.start();
	}
}