Android: how to set click events on ListView?
I'm looking to be able to open up a new view or activity when I click on an item in my ListView.
Currently I have a list of restaurants, and when i click on a particular restaurant I want it to open up another screen that will show its address, google map etc.
What I need help with is knowing how to set click events on the items in the list. At the moment I dont have a database of the items, they're just Strings. Can someone help me with getting me to this stage?
Thanks alot.
package com.example.androidrestaurant;
import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.TextView; import android.app.ListActivity;
public class Dundrum extends ListActivity { TextView selection;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, DUNDRUM));
getListView().setTextFilterEnabled(true);
}
static final String[] DUNDRUM = new String[] {
"Ananda",
"Brambles Cafe", "Brannigans", "Buona Sera",
"Cafe Mao", "Cafe Mimo",
"Dante", "Douglas & Kaldi Terrace Cafe",
"Eddie Rockets",
"Frango'开发者_运维百科s World Cuisine",
"Nando's",
"Overends Restaurant @ Airfield House",
"Pizza Hut",
"Roly Saul",
"Siam Thai","Smokey Joes","Sohag Tandoori",
"TGI Friday","The Rockfield Lounge", "Winters Bar" };
};
You need to do like this :
// Store your listview into local variable
ListView lv = getListView();
lv.setTextFilterEnabled(true);
// Bind onclick event handler
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Put in your code here, what you wanted trigger :)
}
});
If you are using the ListView
in a ListActivity
, override onListItemClick()
. Otherwise, use setOnItemClickListener()
with the ListView
. In either case, you are given a position that is the index into your array.
See here for an sample project.
精彩评论