Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

android - Does a replacement for Gallery widget with View recycling exist?

The default Gallery widget on Android does not recycle views - everytime the view for a new position is called the widget always calls the getView method of the adapter with convertView set to null.

As you scroll backwards and forwards this ends up in lots of views being created, which the recycler component that the Gallery stores them in does not seem to recycle them quickly enough leading to an OOM situation.

You can test this easily with a few large-ish images as your gallery items, but just a TextView will cause it in the end. Put a log statement with a counter in the getView method of your adapter also to see how many new views are created.

Does a third-party widget which behaves like a Gallery but that also implements view recycling exist?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My solution was, in the end, going with @CommonsWare's suggestion to modify the Gallery source code. This is also required copying the following files:

  • AdapterView
  • AbsSpinner

but these are pretty simple.

After that I modified code to do the following:

RecycleBin (AbsSpinner)

  • Place objects in the recycler one after another, rather than according to position
  • Retrieve objects from the bottom of the recycler, regardless of the position requested
  • The existing implementation assumed that each different position in the adapter resulted in a unique view. The changes above are only good if your Gallery contains only one type of item, if not you'll need to add some sort of key based on item type and the amount of that type required

Gallery

  • Used reflection (ugh) to modify the private mGroupFlags variable of ViewGroup to allow child re-ordering - I also set a boolean value indicating whether the field access succeeded which I test before using the component.
  • Removed all calls to mRecycler.clear()
  • The number of items the gallery has to display changes as it scrolls and the existing implementation would clear the recycler when (a) setSelection was called (b) a motion scroll occurred

With these modifications my counter in my newView method in my adapter reached... 7.

Here is the code (Placed in the public domain 2013/08/07 under http://en.wikipedia.org/wiki/WTFPL)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...