java - Identify dynamically added views for OnclickListener -
i have problem programming android:
i adding textviews layout dynamically reading out data out of arraylist. got different textviews on layout. want set onclicklistener each of them , start different activities onclicklistener depending on textview clicked. problem don't know how identify textviews. add them like:
while(i<list.size()) { string name = list.get(i).getname(); textview txtviewname = new textview(this); txtviewname.settext(name); layout.add(txtviewname); i++; }
everything works, how can set onclicklistener each txtview , how identify them?
thanks help!
the easiest way set onclicklistener
anonymous inner class inside loop, , whatever's appropriate view:
final int viewnum = i; txtviewname.setonclicklistener(new onclicklistener() { @override public void onclick(view view) { toast.maketext(mainactivity.this, "you clicked on view "+viewnum, toast.length_short).show(); } });
this example, shows how listener act differently each view. means don't need else identify views, because can use whatever need inside loop when you're setting listener.
a couple of things note:
- i've assumed enclosing activity called
mainactivity
, of course you'll need change suit case. - anonymous inner classes can access
final
local variables. why i've setfinal int viewnum = i
, , used instead ofi
. have same effect naturally expect if allowed usei
. you'd need similar trick if wanted refer other local variables insideonclick()
method.
Comments
Post a Comment