【问题标题】:What are the pitfalls when using static functions? Like in this Android code使用静态函数有哪些陷阱?就像在这个 Android 代码中一样
【发布时间】:2010-09-30 16:18:17
【问题描述】:

我在this example 的getView() 方法中使用了一个静态函数来下载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;
                }

【问题讨论】:

  • 静态方法是否保持状态? (使用静态变量、单例等)

标签: java android listadapter expandablelistadapter static-functions


【解决方案1】:

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

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

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

这与静态方法无关,与应用图像有关。行被回收。因此,如果下载图像的时间过长,则可能不再需要该图像——ImageView 应该显示其他图像。解决此问题的一种方法是将ImageView 所需图像的URL 粘贴在setTag()ImageView 本身上。下载完成后,在将下载的图像放入ImageView 之前,调用getTag() 并比较URL。如果标记中的 URL 与下载的 URL 不同,请不要更新 ImageView,因为这将用于错误的图像。

【讨论】:

    【解决方案2】:

    我通过不重用渲染器来解决这个问题(这听起来确实比它更痛苦),而是使用带有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;
    }
    

    你必须将_renderers[position]强制转换为WeakReference,因为java不支持带有泛型的数组,所以_renderers是一个Objects数组

    【讨论】:

    • 我会考虑你的回答并提供反馈,当我完成它时。
    【解决方案3】:

    如果静态函数没有副作用,那么使用起来应该是完全安全的。根据您对该函数的描述,它似乎确实有副作用,因此您需要确保从不同的地方调用该函数不会引起任何冲突。如果没有看到这个功能,我真的无法告诉你更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-11
      • 2011-06-10
      • 2015-07-07
      • 2020-04-15
      • 1970-01-01
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多