android - textview background not changing after clicking -
i wrote code changing textview background after clicking text, background color did not change other textview background color change. understand recyclerview reuse view, set notifyitemchanged()
avoid reset view.
public class myadapter extends recyclerview.adapter<myadapter.myviewholder>{ private list<string> innertext; private context mcontext; public myadapter(list<string> items,context context){ this.innertext = items; this.mcontext = context; } @override public myviewholder oncreateviewholder(viewgroup parent, int viewtype) { view v = layoutinflater.from(parent.getcontext()).inflate(r.layout.background_color, parent, false); myviewholder holder = new myviewholder(v); return holder; } @override public void onbindviewholder(myviewholder holder, int position) { string s = innertext.get(position); holder.t1.settext(s); } @override public int getitemcount() { return innertext.size(); } class myviewholder extends recyclerview.viewholder implements view.onclicklistener{ public textview t1; public myviewholder(view itemview) { super(itemview); t1 = (textview)itemview.findviewbyid(r.id.t1); t1.setonclicklistener(this); } @override public void onclick(view v) { int pos = getadapterposition(); t1.setbackgroundcolor(color.parsecolor("#455a64")); notifyitemchanged(pos); } } }
if need more code me please let me know.
this not tried code explain logic you:-
public class myadapter extends recyclerview.adapter { private list<string> innertext; private context mcontext; private boolean[] checked={false}; public myadapter(list<string> items, context context) { this.innertext = items; this.mcontext = context; checked = new boolean[items.size()]; } @override public myviewholder oncreateviewholder(viewgroup parent, int viewtype) { view v = layoutinflater.from(parent.getcontext()).inflate(r.layout.background_color, parent, false); myviewholder holder = new myviewholder(v); return holder; } @override public void onbindviewholder(recyclerview.viewholder holder, int position) { string s = innertext.get(position); ((myviewholder)holder).t1.settext(s); if(checked[position]){ ((myviewholder)holder).t1.setbackgroundcolor(color.parsecolor("#455a64")); } } @override public int getitemcount() { return innertext.size(); } class myviewholder extends recyclerview.viewholder implements view.onclicklistener { public textview t1; public myviewholder(view itemview) { super(itemview); t1 = (textview) itemview.findviewbyid(r.id.t1); t1.setonclicklistener(this); } @override public void onclick(view v) { int pos = getadapterposition(); checked[pos] = true; notifyitemchanged(pos); } }
}
basically have store position has been clicked in boolean array , set color in onbindview checking if has been clicked, recyclerview doesnt work way u think, recycle views
Comments
Post a Comment