How to get position of item clicked on listview?
my activity code to get position of item on ListActivity to update status checked to database
public class ViewList extends ListActivity {
private ListViewAdapter lAdapter;
DBAdapter db;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
db = new DBAdapter(this);
db.open();
Cursor cursor = db.fetchAllDeliveryItem();
lAdapter = new ListViewAdapter(getApplicationContext(),cursor);
//Toast.makeText(getApplicationContext(), cursor.getString(1), Toast.LENGTH_SHORT).show();
setListAdapter(lAdapter);
}
private class ListViewAdapter extends CursorAdapter{
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return super.getView(position, convertView, parent);
}
public ListViewAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tvListText = (TextView)view.fin开发者_如何学运维dViewById(R.id.label);
CheckBox cbListCheck = (CheckBox)view.findViewById(R.id.check);
tvListText.setText(cursor.getString(cursor.getColumnIndex("itemname")));
**cbListCheck.setChecked((cursor.getInt(cursor.getColumnIndex("delivered"))==0? false:true));
cbListCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
db.updateItem(position);**
}
});
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return li.inflate(R.layout.receiverow, parent, false);
}
You need to call setOnItemClickListener on your ListView. Its callback function includes the position of the view that is clicked as a argument. Here is an example:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id){
// DO STUFF HERE
}
});
Edit: Sorry I thought you were using a ListView not a ListActivity. Its even easier for a ListActivity as you simply implement the following method in your ListActivity:
onListItemClick (ListView l, View v, int position, long id)
In the case of ListActivity, you can override the method onListItemClick in the ListActivity class.
When you extend ListActivity you can override the onListItemClick method like this:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Do stuff
}
you should implement
onListItemClick
and override the method :
@Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i("the Item clicked is at position : ", position);
}
精彩评论