代码之家  ›  专栏  ›  技术社区  ›  OneWorld

使用静态函数时有哪些陷阱?就像这个安卓代码

  •  0
  • OneWorld  · 技术社区  · 15 年前

    我在的getView()方法中使用 this example 下载ImageView源代码的静态函数。稍后将包括线程。不过,我想知道在一般情况下如何保存静态函数的使用是在这种情况下。

    因为我经历过,在某些情况下(当我快速滚动时),图像会混淆。

        /**
        * Is called, when the ListAdapter requests a new ListItem, when scrolling. Returns a listItem (row)
        */
            public View getView(int position, View convertView, ViewGroup parent) {
                            View v = convertView;
                            if (v == null) {
                                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                v = vi.inflate(R.layout.row, null);
                            }
                            Order o = items.get(position);
                            if (o != null) {
                                    TextView tt = (TextView) v.findViewById(R.id.toptext);
    
                                    if (tt != null) {
                                          tt.setText("Name: "+o.getOrderName());                            }
    
    //At this point I use a static function to download the bitmap to set it as source of an ImageView
    
                            }
                            return v;
                    }
    
    3 回复  |  直到 15 年前
        1
  •  1
  •   Thomas Vervest    15 年前

    WeakReference 物体。这使您的列表速度更快,并且防止您在渲染器上设置现在用于其他数据的图像,同时如果内存不足,GC有机会删除未使用的列表项。

    public View getView(int position, View convertView, ViewGroup parent) {
        Renderer result = null;
        WeakReference<Renderer> wr = (WeakReference<Renderer>) _renderers[position];
        if (ref != null)
            result = wr.get();
    
        if (result == null) {
            result = new Renderer(_context);
            // set the texts here and start loading your images
            _renderers[position] = new WeakReference<Renderer>(result);
        }
        return result;
    }
    

        2
  •  2
  •   CommonsWare    15 年前

    我在本例的getView()方法中使用了一个静态函数来下载ImageView的源代码。

    我在那篇博文的任何地方都没有看到静态方法。

    因为我经历过,在某些情况下(当我快速滚动时),图像会混淆。

    这与静态方法无关,而与应用图像有关。行被回收。因此,如果下载一个映像花费的时间太长,可能是不再需要该映像了 ImageView 应该显示其他图像。解决这个问题的一种方法是粘贴 在里面 setTag() 图片框 它自己。下载完成后,将下载的图像放入 图片框 getTag() 并比较URL。如果标记中的URL与下载的URL不同,请不要更新 图片框

        3
  •  0
  •   Mike Baranczak    15 年前

    如果静态函数没有副作用,那么使用它应该是完全安全的。根据您对函数的描述,它似乎确实有副作用,因此您需要确保从不同位置调用函数不会导致任何冲突。我真的不能告诉你更多没有看到的功能。

    推荐文章