android - Recyclerview make the last added item be the selected item? -
i have horizontal recyclerview displays bitmaps. way implemented have imageview , recyclerview underneath it. selected item displayed on image view. selected image view given blue background indicate selected. can choose images gallery , each time new image selected, want scroll last position , make item selected.
the list of images maintained in array list , each time new image added, add image list , notifydatachanged().
currently when binding view, toggle visibility of blue background in
public void onbindviewholder(final myrecyclerviewholder holder, int position) { }
but problem is, if child off screen, bind view not called , dont scroll new position. read through documentation of recycler view , not figure out how scroll particular child view. not there smoothscrollto method question trigger ?
there 1 solution:
in
recyclerview
adapter, add variableselecteditem
, methodssetselecteditem()
:private static int selecteditem = -1; ... ... public void setselecteditem(int position) { selecteditem = position; }
in
onbindviewholder(...)
, add:@override public void onbindviewholder(viewholder holder, final int position) { ... ... if(selecteditem == position) holder.itemview.setselected(true); }
now can scroll specific item , set selected programmatically by:
myrecyclerviewadapter.setselecteditem(position_scrollto); myrecyclerview.scrolltoposition(position_scrollto);
for example, want scroll last position , make selected, just:
int last_pos = myrecyclerviewadapter.getitemcount() - 1; myrecyclerviewadapter.setselecteditem(last_pos); myrecyclerview.scrolltoposition(last_pos);
[update]
to add item , make selected, should have additem(...)
method in adapter, add item item list. after adding item, refresh list , scroll new added/latest item:
myrecyclerviewadapter.additem(...); myrecyclerviewadapter.notifydatasetchanged(); myrecyclerviewadapter.setselecteditem(myrecyclerviewadapter.getitemcount() - 1); myrecyclerview.scrolltoposition(myrecyclerviewadapter.getitemcount() - 1);
hope help!
Comments
Post a Comment