<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/layoutMain" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <ProgressBar android:id="@+id/progressBar1" style="?android:attr/progressBarStyleHorizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:max="100"/> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="开始" /> </LinearLayout>
package com.moon.hello2; import java.util.Calendar; import android.R.anim; import android.R.integer; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.DatePicker; import android.widget.ProgressBar; import android.widget.DatePicker.OnDateChangedListener; import android.widget.TextView; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; public class MainActivity extends Activity { private int status = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_main); final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1); // final ProgressBar progressBar2 = // (ProgressBar)findViewById(R.id.progressBar2); final Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 0x111) { progressBar.setProgress(MainActivity.this.status); // progressBar2.setProgress(MainActivity.this.status); } } }; Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub new Thread() { public void run() { while (MainActivity.this.status < 100) { doWork(); Message message = new Message(); message.what = 0x111; handler.sendMessage(message); } } }.start(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public void doWork() { status++; try { Thread.sleep(100); } catch (Exception e) { // TODO: handle exception } } }