java - Android: Is it possible to call a method directly from setOnClickListener()? -
i dynamically creating buttons , ideally able have method run if button pressed.
is following possible?
private void somemethod(int id){ //on button pressed id } private void othermethod(){ for( program element : somelist) { addbutton.setonclicklistener(somemethod(element.getid)); } }
obviously thats mock of code illustrate question. know can instantiate new class seems should able call method although far keep getting errors attempts.
i have had around web can't find answer this, thought ask here.
setonclicklistener
defines happen when button clicked. setting multiple times same button meaningless; last 1 set active one.
to call method within listener, declare anonymous class override:
addbutton.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { somemethod(...); } });
if you're trying set multiple buttons similar functionality, need loop through buttons (in list, say), , set each of onclicklistener
s. achieve differing variable per button, use view
's tag:
for (button b : buttons) { b.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { somemethod(v.gettag()); } }); }
now can set button
's tag
property in xml (or manually) whatever wish , passed listener (and method).
Comments
Post a Comment