Reputation: 25
How do you set up an onClickListener for a list view so that each list view item takes you to a different intent?
Upvotes: 1
Views: 411
Reputation: 18489
If you are extending ListActivity then you can do something like this:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Intent intent = new Intent(present_activity.this,target_activty.class);
intent.putExtras("key",item);
startActivity(intent);
}
Hope this helps..:)
Upvotes: 2
Reputation: 3433
Set the listener like this:
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
String item = (String) myListView.getAdapter().getItem(position);
Intent intent = new Intent(getBaseContext(), MyActivity.class);
intent.putExtras("name", item);
startActivity(intent);
}
});
EDIT
You use the position
that you receive in the listener to get the item in the list at that position. Then you can bundle the item with the Intent
and send it to the Activity
(see code above with putExtra
)
Upvotes: 0
Reputation: 1476
If you are populating the list through an adapter you can use onListItemClick() which will give you the listView, the view clicked, and the position in the list.
From there you can use a switch on the position to start the different activities. Or if your listview is more dynamic you can have the view in the list save which activity it wants to open in its tag. (view.setTag("acivityName")) and use something like this to start the activity:
String activityName = view.getTag();
i = new Intent(v.getContext(), Class.forName(activityName));
startActivity(i);
Upvotes: 0