java - Android: GridView resetting position in getView -
i'm populating gridview list of stages, 4. when calling getview(...)
0, 1 , 2 load fine, showing correct position number.
however, on position 3 number reset 0, giving me list: 0, 1, 2, 0
.
public class examplegrid extends baseadapter{ private context mcontext; public examplegrid(context c){ mcontext = c; } @override public int getcount() { return 20; } @override public object getitem(int pos) { return null; } @override public long getitemid(int pos) { return 0; } @override public view getview(int position, view convertview, viewgroup parent) { final button levelbutton; if (convertview == null) { string positiontext = position + ""; levelbutton = new button(mcontext); levelbutton.settext(mcontext.getresources().getstring(r.string.mm_stage) + positiontext); levelbutton.setlayoutparams(new gridview.layoutparams(viewgroup.layoutparams.wrap_content, viewgroup.layoutparams.wrap_content)); } else { levelbutton = (button) convertview; } return levelbutton; } }
this prints 0, 1, 2, 0
. if set getcount()
method return larger value, pattern repeated. e.g.: 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, ...
update: changed code more generic example. numbers loaded fine @ first scroll down list, lose order.
finally solved keeping reference buttons in baseadapter
, using reference instead of checking convertview
getview(...)
method. note mbuttons
:
public class examplegrid extends baseadapter{ private context mcontext; private button[] mbuttons; public examplegrid(context c){ mcontext = c; mbuttons = new button[getcount()]; } @override public int getcount() { return 20; } @override public object getitem(int pos) { return mbuttons[pos]; } @override public long getitemid(int pos) { return 0; } @override public view getview(int position, view convertview, viewgroup parent) { final button levelbutton; if (mbuttons[position] == null){ string positiontext = position + ""; levelbutton = new button(mcontext); levelbutton.settext(mcontext.getresources().getstring(r.string.mm_stage) + positiontext); levelbutton.setlayoutparams(new gridview.layoutparams(viewgroup.layoutparams.wrap_content, viewgroup.layoutparams.wrap_content)); mbuttons[position] = levelbutton; } else { levelbutton = mbuttons[position]; } return levelbutton; } }
Comments
Post a Comment