android - returning id of a listview item by clicking on a button -
want custom listview in android studio each item has button. clicking on button should return id of item in listview button in main activity.
had added layout xmls , problem in mainactivity.java , class needed in it.
in adapter's getview
method set button's tag e.g.:-
public view getview(int position, view convertview, viewgroup parent) { button yourbutton = (button) view.findviewbyid(r.id.yourbuttonid); yourbutton.settag(position); .......
in button's onclick handling use int position = (int) view.gettag();
retrieve position should correlate array's index.
there 2 main ways of handling button's onclick
in listview
1) specify method used in button's xml (only since api level 4) , provide handling method in invoking activity:-
example xml :-
<button android:id="@+id/mybutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="click" android:onclick="mybuttonclicked" />
example handler in activity includes respective listview
..... public mybuttonclicked(view view) { int position = (int) view.gettag(); .... }
2) include setting listener , onclick
handling in listview
's adapter
's getview
method.
example :-
public view getview(int position, view convertview, viewgroup parent) { button yourbutton = (button) view.findviewbyid(r.id.yourbuttonid); yourbutton.settag(position); yourbutton.setonclicklistener(new onclicklistener() { public void onclick(view view) { int position = view.gettag(); } });
you may wish have @ these, cover above in more detail
i find xml method convenient. utilise style
basis buttons (i use textview buttons) have single method (as set in style) incorporate respective activities. copes admirably multiple buttons per listview item.
Comments
Post a Comment