在寫PagerAdapter的時候,需要重寫instantiateItem(ViewGroup container ,int position)
此方法中,將需要加載的View,添加到container中。
PagerAdapter不能直接使用像ListView那樣的ViewHolder,來實現View的復用。
所以,如果每次加載,都要新建一個View出來就會很占用內存。
如果你的View都是一樣的,比如都是ImageView,那么就可以使用一個List將回收的View存起來
再次加載的時候,優先從回收List中加載,不必再去new.
大致的邏輯如下:
private
LinkedList
<
View
>
recycledViews
=
new
LinkedList
<
View
>
()
;
public
Object
instantiateItem
(
ViewGroup
container
,
int
position
)
{
// TODO Auto-generated method stub
CustomImage
imageView
=
null;
if
(
debug
)
Log
.
e
(
TAG
,
"PagerAdapter : instantiateItem"
+
"position is "
+
String
.
valueOf
(
position
)
+
"ChildCount is:"
+
container
.
getChildCount
())
;
if
(
recycledViews
!=
null
&&
recycledViews
.
size
()
>
0
)
{
imageView
=
(
CustomImage
)
recycledViews
.
getFirst
()
;
recycledViews
.
removeFirst
()
;
}
else
{
imageView
=
new
CustomImage
(
mContext
)
;
}
imageView
.
setImageResource
(
resids
.
get
(
position
))
;
container
.
addView
(
imageView
)
;
return
imageView
;
}
@Override
public
void
destroyItem
(
ViewGroup
container
,
int
position
,
Object
object
)
{
// TODO Auto-generated method stub
if
(
debug
)
Log
.
e
(
TAG
,
"PagerAdapter : destroyItem"
+
"position is"
+
String
.
valueOf
(
position
)
+
"ChildCount is:"
+
container
.
getChildCount
())
;
((
ViewGroup
)
container
)
.
removeView
((
View
)
object
)
;
if
(
object
!=
null
)
{
recycledViews
.
addLast
((
View
)
object
)
;
}
}
上面的CustomView是我自定義的一個ImageView,可以用任意的View代替。效果一樣的。