按下更新按钮,每隔1S自动更新进度条,更新到100%自动消失
activity:
package com.example.trd;
import android.os.Bundle;import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
Button btn=null;
private ProgressBar pb=null;
private int progress=0;
Handler h=new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
pb=(ProgressBar)findViewById(R.id.bar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void hhhhh(View v){
MyThread t=new MyThread();
t.start();
}
class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while(progress<pb.getMax()){
progress+=10;
pb.setProgress(progress);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
if(progress>=pb.getMax())
h.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
});
}
}
}
}
xml
<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=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView1"
android:layout_marginBottom="181dp"
android:text="更新ing"
android:onClick="hhhhh"/>
<ProgressBar
android:id="@+id/bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:layout_below="@id/button1"
android:max="100"
/>
</RelativeLayout>