Reputation: 23
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
Upvotes: 0
Views: 3700
Reputation: 14007
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"
Upvotes: 0
Reputation: 6579
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
Upvotes: 2