我的列表视图的代码如下:
CourseDataAdapter mCourseListAdapter = new CourseDataAdapter(this, R.layout.coursesearchviewrow, mCursor);
list.setAdapter(mCourseListAdapter);
list.setItemsCanFocus(false);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
long index = arg0.getSelectedItemId();
listDialog.dismiss();
}
});
我使用自定义的游标适配器,我的代码在这里:
public class CourseDataAdapter extends ResourceCursorAdapter {
private TextView courseType;
private TextView courseDays;
private TextView courseTime;
public CourseDataAdapter(Context context, int layout, Cursor c) {
super(context, layout, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
return mInflater.inflate(R.layout.coursesearchviewrow, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
courseType = (TextView) view.findViewById(R.id.course_search_type_view);
courseDays = (TextView) view.findViewById(R.id.course_search_days_view);
courseTime = (TextView) view.findViewById(R.id.course_search_time_view);
courseType.setText(cursor.getString(cursor.getColumnIndex(CourseDbAdapter.KEY_TYPE)));
courseDays.setText(CourseDataHandler.daysStringProcessor(cursor.getInt(cursor.getColumnIndex(CourseDbAdapter.KEY_DAYS))));
courseTime.setText(CourseDataHandler.courseTimeProcessor(cursor.getString(cursor.getColumnIndex(CourseDbAdapter.KEY_START_TIME)), cursor.getString(cursor.getColumnIndex(CourseDbAdapter.KEY_END_TIME))));
}
}
但是,每次单击列表中的项目时,getSelectedItemId()方法都会返回无效值。
PS。我尝试了getSelectedItemPosition(),它还返回一个无效值,即-1。
那么如何获得我点击的项目的位置?
答案 0 :(得分:1)
正在选择的列表项与按下它的概念不同,在这种情况下不适用。您已经直接将ID传递给了您,这是onItemClick
方法的第4个参数。
答案 1 :(得分:1)
docs onItemClick
具有以下方法签名:
public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)
这似乎是你正在寻找的东西:
position 视图在适配器中的位置。
答案 2 :(得分:0)
我假设你想要这个位置,这样你就可以得到存储在与listview中该点相关联的游标中的一些数据。你应该做的是将onClickListener赋值移动到bindView方法中,如下所示:
public void bindView(View view, Context context, Cursor cursor) {
courseType = (TextView) view.findViewById(R.id.course_search_type_view);
courseDays = (TextView) view.findViewById(R.id.course_search_days_view);
courseTime = (TextView) view.findViewById(R.id.course_search_time_view);
courseType.setText(cursor.getString(cursor.getColumnIndex(CourseDbAdapter.KEY_TYPE)));
courseDays.setText(CourseDataHandler.daysStringProcessor(cursor.getInt(cursor.getColumnIndex(CourseDbAdapter.KEY_DAYS))));
courseTime.setText(CourseDataHandler.courseTimeProcessor(cursor.getString(cursor.getColumnIndex(CourseDbAdapter.KEY_START_TIME)), cursor.getString(cursor.getColumnIndex(CourseDbAdapter.KEY_END_TIME))));
view.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
//in here you now have access to the cursor
}
});
}