android 进度条

xiaoxiao2021-02-28  92

进度条

给大家带来一个进度条的方法

先定义一个进度条

<ProgressBar style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/pb_progressbar_bar" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_progressbar_num" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载" android:onClick="download" />

这里定义了一个简单的进度条 

然后进入.java文件

public class MainActivity extends AppCompatActivity { private ProgressBar pb_progressbar_bar; private TextView tv_progressbar_num; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.zuoye_01); pb_progressbar_bar=(ProgressBar) findViewById(R.id.pb_progressbar_bar); tv_progressbar_num=(TextView) findViewById(R.id.tv_progressbar_num); }

然后接收消息,更新界面

/** * ANR * application not responsing 应用程序未响应 * why:在主线程中执行了耗时的操作 * how:在子线程中执行耗时操作 * @param view */ public void download(View view){ new MyThread().start(); } Handler handler=new Handler(){ //接受消息,更新界面 @Override public void handleMessage(Message msg) { super.handleMessage(msg); int i=msg.what; tv_progressbar_num.setText(i+""); } };

最后执行线程,设置线程的时间

private class MyThread extends Thread{ @Override public void run() { super.run(); for (int i = 0; i <=100 ; i++) { pb_progressbar_bar.setProgress(i); handler.sendEmptyMessage(i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }

最后执行项目  结果就出来了,

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

最新回复(0)