2012-11-18 29 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 
} 

哪个更干净。