Handler与ProgressBar 例子
MainActivity
package ray.com.hander_progressbar;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private ProgressBar proBar = null;
private Button button = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
proBar = (ProgressBar) findViewById(R.id.probar);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
proBar.setVisibility(View.VISIBLE);
// 防止重复点击post很多线程进去
if (proBar.getProgress() > 0) {
return;
}
handler.post(runnable);
}
});
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
proBar.setProgress(message.arg1);
handler.post(runnable);
}
};
Runnable runnable = new Runnable() {
int i = 1;
@Override
public void run() {
i++;
Message message = handler.obtainMessage();
message.arg1 = i;
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.sendMessage(message);
if (i > 100) {
handler.removeCallbacks(this);
i = 1;
}
}
};
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<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="ray.com.hander_progressbar.MainActivity">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:id="@+id/probar"
android:visibility="gone"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Start"/>
</RelativeLayout>