android ProgressBar 进度条

来源:互联网 发布:python 支持向量机 编辑:程序博客网 时间:2024/04/26 14:50

一个水平进度条,一个圆形进度条,使用线程模拟耗时操作并发送消息,用handler接收消息,在进度条显示进度


1.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageview1"
        android:src="@drawable/ic_launcher"
        />
    <ProgressBar 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progressbar1"
        android:max="100"
        style="@android:style/Widget.ProgressBar.Horizontal"
        />


    <ProgressBar 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressbar2"
        style="?android:attr/progressBarStyleLarge"
        />
</LinearLayout>


2.MainActivity

private ProgressBar mHorizonP;
private ProgressBar mCircleP;
private int mProgressStatus = 0;
private Handler mHandler;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.processbar);
mHorizonP = (ProgressBar) findViewById(R.id.progressbar1);
mCircleP  = (ProgressBar) findViewById(R.id.progressbar2);

mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 0x111) {
mHorizonP.setProgress(mProgressStatus);
} else {
Toast.makeText(MainActivity.this, "耗时操作已经完成", Toast.LENGTH_SHORT).show();
mHorizonP.setVisibility(View.GONE);
mCircleP.setVisibility(View.GONE);
}
}
};

new Thread(new Runnable() {
@Override
public void run() {
while (true) {
mProgressStatus = doWork();
Message m = new Message();
if (mProgressStatus < 100) {
m.what = 0x111;
mHandler.sendMessage(m);
} else {
m.what = 0x110;
mHandler.sendMessage(m);
break;
}
}

}

private int doWork() {
mProgressStatus += Math.random() * 10;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return mProgressStatus;
}

}).start();

}

0 0
原创粉丝点击