欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android常用控件七之ProgressBar的代码用法

程序员文章站 2022-04-28 08:55:41
...

效果图:

Android常用控件七之ProgressBar的代码用法


布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="下载"
        android:onClick="ok"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv"/>


</LinearLayout>


Java代码:

package com.zking.laci.android07;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * Created by Laci on 2017/6/7.
 */

public class ProgressActivity extends AppCompatActivity{

    private ProgressBar pb;
    private TextView tv;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progressbar);

        //通过ID拿到相对应的控件
        pb = (ProgressBar) findViewById(R.id.progressBar);
        tv = (TextView) findViewById(R.id.tv);
    }

    public void ok(View v){
            new MyThread().start();
    }

    //接收消息,更新UI界面
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int i=msg.what;
            //给文本框设置值
            tv.setText(i+"");
        }
    };

    class MyThread extends Thread{
        @Override
        public void run() {
            super.run();
            for (int i = 0; i <=100 ; i++) {
                //控制进度条的走动
                pb.setProgress(i);
                //在子线程中发消息
                handler.sendEmptyMessage(i);
                try {
                    //每0.1秒停止
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

}