Android中通过Handler实现进度条的实时更新

MainActivity代码:

import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;


public class MainActivity extends Activity {
private ProgressBar progressBar;
private Button btn;
private Handler handler;
private int i = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == 0x123) {
if (i <= 100) {
progressBar.setProgress(i);
i++;
}
}
}
};
new Timer().schedule(new TimerTask() {


@Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(0x123);
}
}, 0, 1000);
}
});


}
}

activity_main布局

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


            android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="进度条的更新" />


            android:id="@+id/progressBar"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100" />



你可能感兴趣的:(Android中通过Handler实现进度条的实时更新)