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

xiaoxiao2021-02-28  88

效果图:

布局代码:

<?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(); } } } } }

转载请注明原文地址: https://www.6miu.com/read-57217.html

最新回复(0)