39

I am new to android, I have a code in which I have placed buttons in list view. My list is as..

Number | Name | ID (visibility = gone) | Level | button1 | button2

Function is different in button 1 and button 2 case. I have applied listeners on buttons but when I try to get the ID from list it always shows me the last id.

How to know which button was clicked, name and id of related field.

I have placed buttons and listener on buttons in getView(...) function.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
AZ_
  • 21,688
  • 25
  • 143
  • 191

1 Answers1

94
final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

cwc
  • 8,687
  • 2
  • 20
  • 19
Adesara
  • 1,568
  • 1
  • 13
  • 9
  • I have a button in my listView and action listener is attached on the button. I know that on which button action was performed but how to get the id on which it was clicked ??? please look at question again. – AZ_ Dec 22 '10 at 13:24
  • I don't want to put action listener on list, rather on child of listView button. – AZ_ Dec 22 '10 at 13:24
  • lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView myAdapter, View myView, int myItemInt, long mylng) { Button btnFetchId = (Button) findViewById(R.id.button01); } } – Adesara Dec 22 '10 at 13:34
  • 1
    hey I got it... I simply user btn.setTag() and set the value I want to receive and where I want i simply did btn.getTag() .. – AZ_ Dec 22 '10 at 13:58
  • http://code.google.com/p/android/issues/detail?id=13891 . any workaround ? i think, on every textchange, i'll do a backup of my data, and in onSelect() , i'll get the value in my backup – Laurent Debricon Feb 25 '12 at 17:00
  • got this error in logcat: java.lang.ClassCastException: cannot be cast to java.lang.String – Ahmad Arslan Aug 11 '14 at 12:01