面试题之10秒跑完进度条

 

方式一:使用Handler

 

 

Java代码   收藏代码
  1.  public class ProgressActivity extends Activity implements Runnable {  
  2.     private ProgressBar progress;  
  3.     Handler h = new Handler();  
  4.     private int max=100,current,step;  
  5.   
  6.     @Override  
  7.     protected void onCreate(Bundle savedInstanceState) {  
  8.         super.onCreate(savedInstanceState);  
  9.         setContentView(R.layout.activity_progress);  
  10.         progress = (ProgressBar) findViewById(R.id.progress);  
  11.         progress.setMax(max);  
  12.         progress.setProgress(0);  
  13.         step = max/10;  
  14.         h.post(this);  
  15.       
  16.     }  
  17.   
  18.     @Override  
  19.     protected void onDestroy() {  
  20.         super.onDestroy();  
  21.     }  
  22.   
  23.     @Override  
  24.     public void run() {  
  25.         current = progress.getProgress();  
  26.         progress.setProgress(current+step);  
  27.         h.postDelayed(this1000);  
  28.     }  
  29.   
  30. }  

 


 

 

 

 方式二:使用自定义线程

               有些微不对劲

 

 

Java代码   收藏代码
  1. public class ProgressActivity extends Activity {  
  2.     private ProgressBar progress;  
  3.     private int max = 100, current = 0, step = 0;  
  4.   
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_progress);  
  9.         progress = (ProgressBar) findViewById(R.id.progress);  
  10.         progress.setMax(max);  
  11.         progress.setProgress(0);  
  12.         step = max / 10;  
  13.   
  14.         new Thread(new Runnable() {  
  15.             int i = 1;  
  16.   
  17.             @Override  
  18.             public void run() {  
  19.   
  20.                 try {  
  21.                     while (max != progress.getProgress()) {  
  22.                         Log.i("次数", i + "");  
  23.                         i++;  
  24.                         progress.setProgress(current + step);  
  25.                         current = progress.getProgress();  
  26.                         Thread.sleep(1000);  
  27.                     }  
  28.   
  29.                 } catch (InterruptedException e) {  
  30.                     e.printStackTrace();  
  31.                 }  
  32.             }  
  33.         }).start();  
  34.     }  
  35.   
  36.     @Override  
  37.     protected void onDestroy() {  
  38.         super.onDestroy();  
  39.     }  
  40.   
  41. }  

 

 



 

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值