0

我有带图标的 ListView。每个 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的值等于某个图标的文件名,那么它应该显示图标。我不知道如何编码。我猜我应该在 if-else 中做点什么。

4

2 回答 2

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
 }

哪个更干净。

于 2012-11-18T15:31:46.043 回答
0

HashMap<String, String> item = new HashMap<String, String>();首先,您通过放入getView()做了一件坏事。现在,您正在为重新显示的每一行制作一个新的,这是不需要的。只需删除它并使用:

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

老实说,如果您声称如果该行不应该显示某些内容,那么您的路径不会导致任何事情,我无法理解您如何看到一个图标。如果它运行良好,那么您可以简单地捕获设置时可能发生的异常并且不对其执行任何操作。研究该职位的实际价值data应该会产生洞察力。如果是我,我只会摆null在那些位置上。

一个临时的替代解决方案是为列表视图中的每个位置创建一个布尔数组,然后仅在该位置的值签出时才执行图标设置。

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();
                    }
            }
于 2012-11-18T12:56:56.530 回答