2012-11-18 32 views
0

我有ListView的圖標。每個ListView行都有不同的圖標或者沒有圖標。android listview獲取正確的圖標

我能夠得到正確的圖標的行應該有他們,但問題是,在行中應該沒有任何圖標有一些圖標。

public View getView(int position, View convertView, ViewGroup parent) { 
    // TODO Auto-generated method stub 
    View vi=convertView; 
     if(convertView==null) 
      vi = inflater.inflate(R.layout.list_item, null); 

     TextView title = (TextView) vi.findViewById(R.id.name); 
     ImageView icon = (ImageView) vi.findViewById(R.id.icon); 

     HashMap<String, String> item = new HashMap<String, String>(); 
     item = data.get(position); 

     String imgPath = ASSETS_DIR + item.get(myTable.KEY_PIC) + ".png"; 

      try { 
       Bitmap bitmap = BitmapFactory.decodeStream(vi 
         .getResources().getAssets().open(imgPath)); 
       icon.setImageBitmap(bitmap); 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

     title.setText(item.get(myTable.KEY_NAME)); 

    return vi; 
} 

KEY_PIC總是有一個值,如果KEY_PIC的值等於一些圖標的文件名才把它應該顯示的圖標。我不知道如何編碼。我應該做一些事情,如果我猜。

+0

爲什麼一行的「KEY_PIC」有一個值,如果該行不應該有一個圖標集?它的價值是什麼?如果它是一個有效的路徑,將會設置一個圖標。你有沒有檢查你的佈局xml中沒有默認的源代碼,它包含'icon'ImageView? – ottel142

+0

我的xml佈局沒有默認的源代碼。 – windblow

+0

「KEY_PIC」用於在我的項目中找到其他東西(同名但位置不同)所以我不必在我的xml資源文件(數據庫)中添加更多信息。 – windblow

回答

0

首先,您已將HashMap<String, String> item = new HashMap<String, String>();放入您的getView()中,做了一件壞事。現在你正在爲每一行重新顯示一個新的,這是不需要的。只是刪除它,並使用:

String imgPath = ASSETS_DIR + data.get(position).get(myTable.KEY_PIC) + ".png"; 

老實說我不明白是怎麼回事,你看到一個圖標,如果你要求你的路徑不會導致任何東西,如果是不應該的行展示一些東西。如果它運行良好,那麼您可以簡單地捕捉設置時可能發生的異常,並對其執行任何操作。研究該位置的data的實際價值應該能夠產生洞察力。如果是我,我只需在這些位置放置null

臨時替代解決方案是爲您的listview中的每個位置創建一個布爾數組,然後只在該位置的值檢出時才執行圖標設置。

boolean[] varIcon = { 
      true, 
      false, 
      false, 
      true, 
      false, 
      true }; 
// ... 
// then in the getView() now; 


if (varIcon[position] == true) { 
       String imgPath = ASSETS_DIR + data.get(position).get(myTable.KEY_PIC) + ".png"; 
       try { 
         Bitmap bitmap = BitmapFactory.decodeStream(vi 
           .getResources().getAssets().open(imgPath)); 
         icon.setImageBitmap(bitmap); 

        } catch (IOException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
      } 
0

的可能的問題是意見越來越回收和你永遠清除先前設定的圖像,試試這個來證明這一點:

 String imgPath = ASSETS_DIR + item.get(myTable.KEY_PIC) + ".png"; 

     try { 
      Bitmap bitmap = BitmapFactory.decodeStream(vi 
        .getResources().getAssets().open(imgPath)); 
      icon.setImageBitmap(bitmap); 

     } catch (Exception e) { 
      e.printStackTrace(); 
      icon.setImageDrawable(null); 
     } 

然而,依賴於異常處理一個完全有效的結果不是一個好的做法(也不是表現友好的)。我會建議你讓你的myTable.KEY_PIC列返回null,然後你可以這樣做:

String imageName = item.get(myTable.KEYP_PIC); 
if (imageName == null) { 
    icon.setImageDrawable(null); 
} else { 
    //your code 
} 

哪個更乾淨。