tags:

views:

27

answers:

2
final String [] tmp =  new String[]{"Android", "Google};
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_expandable_list_item_1,tmp);
final ListView lv = new ListView(getApplicationContext());
lv.setAdapter(spinnerArrayAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {

 public void onItemClick(AdapterView<?> arg0, View arg1,
   int arg2, long arg3) {
  int i = lv.getSelectedItemPosition();

   Toast toast = Toast.makeText(getApplicationContext(), arg0.toString(),Toast.LENGTH_SHORT);
         toast.show();


 }
});

I don't know how to get the right element by onItemClick.... the var i is allways -1

+1  A: 

You can use:

 public void onItemClick(AdapterView<?> arg0, View v, int item, long id) {
Toast.makeText(getApplicationContext(), "Clicked on item "+item , Toast.LENGTH_SHORT).show();
}

Or in your case, arg2 is the position of the item in the list, arg3 is the row id See: http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html

Barry
Now my App freeze... the item is a int and not a string
hanswurst
item(or arg2) is the position of the item in the ListView, id (or arg3) is the row id for your array, so you can use tmp[(int) arg3] of tmp[(int) id] to get the name of the item.
Barry
A: 

In public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3), arg2 is an int variable containing the position of the clicked item.

If you clicked the second item in your list, your position value would be 1, considering first item to have position 0.

Is it the Text of the item clicked that you want? Then, say you second item has text "Item2". Inside your onItemClick(), do so:

String s = ((TextView)v).getText().toString();

String s will now contain "Item2"

kiki