Andriod【进度条加进度百分比的实现】(线程)


效果如图:

【Andriod【进度条加进度百分比的实现】(线程)】Andriod【进度条加进度百分比的实现】(线程)
文章图片

Andriod【进度条加进度百分比的实现】(线程)
文章图片

①:main页面布局



线程的注意事项:
不能在主线程中执行耗时的操作,只能在子线程中操作
另外,在子线程中不能操作主线程中的控件(ProgressBar除外)

public class MainActivity extends AppCompatActivity { private ProgressBar main_pro_pro1; //进度条 privateint progress; private TextView main_tv_tv1; //进度条百分比 private MyHandler myHandler = new MyHandler(); privateint code = 1; //线程编号 private class MyHandler extends Handler{ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(code == msg.what){ progress++; main_pro_pro1.setProgress(progress); main_tv_tv1.setText(progress+"%"); } } }@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_pro_pro1 = this.findViewById(R.id.main_pro_pro1); main_tv_tv1=this.findViewById(R.id.main_tv_tv1); }public void setProgress(View view) { if(0 == progress){ new MyThread().start(); //触发子线程 }}//耗时操作放在MyThread(子线程) private class MyThread extends Thread{ @Override public void run() { super.run(); while (true){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } if(progress==100){ progress=0; break; } Message msg = new Message(); msg.what=1; myHandler.sendMessage(msg); //Handler}} }}


    推荐阅读