功能:点击start Button 进度条每一秒前进一格
MainActivity.java
package com.example.activity06;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private Button startButton=null;
private Button endButton=null;
private ProgressBar bar=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar=(ProgressBar)findViewById(R.id.bar);
startButton=(Button)findViewById(R.id.startButton);
startButton.setOnClickListener(new StartButtonListener());
}
class StartButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
bar.setVisibility(View.VISIBLE);
updateBarHandler.post(updateThread);
}
}
Handler updateBarHandler =new Handler(){
public void handleMessage(android.os.Message msg) {
bar.setProgress(msg.arg1);
updateBarHandler.post(updateThread);
}
};
Runnable updateThread=new Runnable(){
int i=0;
@Override
public void run() {
// TODO Auto-generated method stub
i=i+10;
Message msg=updateBarHandler.obtainMessage();
msg.arg1=i;
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
updateBarHandler.sendMessage(msg);
if(i==100){
updateBarHandler.removeCallbacks(updateThread);
}
}
};
@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;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ProgressBar
android:id="@+id/bar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<Button
android:id="@+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="start"
/>
</LinearLayout>