欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android 在子線程中更新UI的幾種方法示例

 更新時間:2017年08月23日 11:37:54   作者:一直在進(jìn)步的李哈哈  
本篇文章主要介紹了Android 在子線程中更新UI的幾種方法示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。

本文介紹了Android 在子線程中更新UI的幾種方法示例,分享給大家,具體如下:

方式一:Handler和Message

① 實例化一個Handler并重寫handlerMessage()方法

private Handler handler = newHandler() {
    public void handleMessage(Message msg) {
          // 處理消息
    super.handleMessage(msg);
    switch (msg.what) {
    case 1:
      button1.setText("點擊安裝");
      break;
    case 2:
      button1.setText("打開");
      break;
    }
    };
 }; 

② 在子線程中獲取或創(chuàng)建消息,并使用handler對象發(fā)送。

Message msg = handler.obtainMessage();
msg.what = 1;
handler.sendMessage(msg);

方式二:在子線程中直接調(diào)用Activity.runOnUiThread(Runnable action)方法

runOnUiThread(new Runnable() {
  @Override
  public void run() {
    // 更新UI的操作
  }
});

方式三:在子線程中調(diào)用View的post()方法

myView.post(new Runnable() {          
  @Override
  public void run() {
    // 更新UI
    myView.setText(“更新UI”);
  }});

方式四:在子線程中調(diào)用View.PostDelayed(Runnabe,long)

對方式三對補(bǔ)充,long參數(shù)用于制定多少時間后運行后臺進(jìn)程

方式五:Handler的post()方法

① 創(chuàng)建一個Handler成員變量

private Handler handler = new Handler();

② 在子線程中調(diào)動post()方法

handler.post(new Runnable() {           
  @Override
  public void run() {
    // 更新UI
   myView.setText(“更新UI”);
  }});

方式六:AsyncTask

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> 
 //在這里聲明了Params、Progress、Result參數(shù)的類型
 {
   //因為這里不需要使用onPreExecute回調(diào)方法,所以就沒有加入該方法
   
   //后臺線程的目的是更具URL下載數(shù)據(jù)
    protected Long doInBackground(URL... urls) {
      int count = urls.length;//urls是數(shù)組,不止一個下載鏈接
      long totalSize = 0;//下載的數(shù)據(jù)
     for (int i = 0; i < count; i++) {
       //Download是用于下載的一個類,和AsyncTask無關(guān),大家可以忽略他的實現(xiàn)
       totalSize += Downloader.downloadFile(urls[i]);
       publishProgress((int) ((i / (float) count) * ));//更新下載的進(jìn)度
       // Escape early if cancel() is called
       if (isCancelled()) break;
     }
     return totalSize;
   }
 
   //更新下載進(jìn)度
   protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
   }
 
   //將下載的數(shù)據(jù)更新到UI線程
   protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
   }
 }

對于一般的只是簡單更新ui,情形不復(fù)雜的,使用方式二三就可以了,但是當(dāng)情形比較復(fù)雜,還是推薦使用handler。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論