4

有沒有一種方法可以將圖像設置爲ListView內的ImageView?在此,我使用SimpleCursorAdapter來顯示所有字段,並使用ViewBinder將圖像位圖設置爲ImageView。該圖像使用AsyncTask下載。我寫的代碼如下:使用SimpleCursorAdapter和ViewBinder在ListView項目中設置圖像

private void updateTimelineUI() { 
     Cursor data = dbHelper.query(Constants.TABLE_NAME, null, null); 
     if (data.moveToFirst()) { 
      adapter = new SimpleCursorAdapter(this, R.layout.tweet_row, data, new String[] {Constants.CREATED_TIME, Constants.USERNAME, Constants.PROFILE_IMAGE, Constants.TWEET}, new int[] {R.id.time, R.id.username, R.id.userImageView, R.id.tweetMessage}); 
      SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() { 
       public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
        if(view != null && view.getId() != R.id.userImageView) { 
         return false; 
        } 
       String imageUrlString = cursor.getString(columnIndex); 
       String username = cursor.getString(cursor.getColumnIndex(Constants.USERNAME)); 
       String path = getDir("images", MODE_PRIVATE).getAbsolutePath() + "/" + username + ".png"; 
       ImageDownloader downloader = new ImageDownloader(); 
       downloader.setImageUrlString(imageUrlString); 
       downloader.setImageView(view); 
       downloader.setFilePath(path); 
       downloader.execute(imageUrlString); 
       return true; 
       } 
      }; 
      int index = data.getColumnIndex(Constants.PROFILE_IMAGE); 
      //Log.d(Constants.TAG, "" + index); 
      adapter.setViewBinder(viewBinder); 
      viewBinder.setViewValue(userImageView, data, index); 
      timelineList.setAdapter(adapter); 
     } 
    } 

有沒有一種方法可以將圖像設置爲正確的行使用此方法?

隨着我目前的代碼,圖像下載成功。但是,圖像是隨機設置的。

回答

2

你應該讓自己的適配器應當自SimpleCursorAdapter繼承,因此,您可以用您的自定義設計,使自己的ListView項,併爲其設置的自定義佈局,可以在其中添加任何UI元素,你想包括ImageView的

+0

因此,除了編寫我自己的適配器之外,沒有別的方法嗎?我能夠將圖像設置爲imageView,但圖像隨機更改,所以我想知道是否可以使用當前代碼完成任何操作。 –

+1

問題是,如果你在滾動列表的時候不做自己的適配器,那麼listItem不知道要渲染哪個圖片,這就是爲什麼它會渲染不同的圖像,從而導致每次滾動都會改變圖像。這就是爲什麼你需要實現自己的適配器並跟蹤每個ListItem中的項目。 –

2

我創建了一個繼承自SimpleCursorAdapter的自定義類,如Serdar Dogruyol提及。在這個自定義類裏我@Override bindView。在bindView內部,我打電話super,然後使用view.findViewById獲得我的ImageView的句柄,其中view是傳遞到bindView的參數之一。

相關問題