2010-10-01 21 views
2

我發現這個例子來自Fedor的Lazy load of images in ListView,這絕對是我所需要的。帶圖像的懶惰列表。如何取消線程?

我有一個問題。如果在清除緩存按鈕旁邊會出現一個帶有取消的按鈕。我怎麼能在onClick取消從UI的圖像下載線程?

謝謝。

編輯: 我認爲,它已經有這個方法來實現:

public void stopThread() 
    { 
     photoLoaderThread.interrupt(); 
    } 

但我不知道如何從UI線程訪問它。在UI線程我只能這樣做:

adapter=new LazyAdapter(ctx, someString); 
setListAdapter(adapter); 
在LazyAdapter

public View getView(int position, View convertView, ViewGroup parent) { 
... 
imageLoader.DisplayImage(imagePath, activity, holder.image); 
     return vi; 
} 

和ImageLoader的

public void DisplayImage(String url, Activity activity, ImageView imageView) 
    { 
     if(cache.containsKey(url)) 
      imageView.setImageBitmap(cache.get(url)); 
     else 
     { 
      queuePhoto(url, activity, imageView); 
      imageView.setImageResource(stub_id); 
     }  
    } 

private void queuePhoto(String url, Activity activity, ImageView imageView) 
    { 
     //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. 
     photosQueue.Clean(imageView); 
     PhotoToLoad p=new PhotoToLoad(url, imageView); 
     synchronized(photosQueue.photosToLoad){ 
      photosQueue.photosToLoad.push(p); 
      photosQueue.photosToLoad.notifyAll(); 
     } 

     //start thread if it's not started yet 
     if(photoLoaderThread.getState()==Thread.State.NEW) 
      photoLoaderThread.start(); 
    } 

但我認爲一個明確的方法是從link text

下載源代碼

謝謝你的幫助。

回答

2

只要把

adapter.imageLoader.stopThread(); 

爲「取消」按鈕單擊處理

+0

啊,我很傻。現在我已經看到了有命令的ui上的onDestroy overrite方法。 Fedor,我非常感謝你的例子,它在我的應用程序中幫了我很大的忙,它的作用就像一個魅力。謝謝謝謝。 – Alin 2010-10-01 11:07:57

1

您可以編寫自己的擴展Java Thread類的自定義類。在那裏你實現了一個停止線程本身的公共停止方法。當你創建並開始你的線程時,你持有一個對它的引用,並在取消按鈕的OnClickEventHandler中調用公共停止方法。

+0

你能告訴你實例化的Thread對象的代碼。你在哪裏開始線程? – Flo 2010-10-01 08:35:10