我的ListView有点问题,当它在OnItemLongClickListener中时,它既没有正确的位置也没有id。
ListView正确显示所有条目,但是在长项目上单击它会返回条目总和作为位置(对于我点击的项目不重要)和所有条目的最高ID。 因为这是事情,我无法获得条目的正确ID(我在自定义适配器中有)。我做错了什么?
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
//Here I want to delete the selected entry..
//both position and id are returning the same value:
// when there are three items in the list, the position would be three for all entries,
// while the id would be the value of the latest entry.
showDeleteSingleEntryDialog(id);
return true;
}
});
我使用AsyncTask填充列表视图,如下所示(通过调用片段内的OnCreateView中的AsyncTask)
private class DisplayEntriesAsyncTask extends AsyncTask<Void,Void,Void>{
Cursor data;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... voids) {
data = mDatabaseHelper.getDiaryEntriesCurrentUser(userID);
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
listData = new ArrayList<>();
if (data == null || data.getCount() < 1) {
mTextView.setText("Keine Einträge vorhanden!");
} else {
try {
while (data.moveToNext()){
listData.add(data.getString(1));
}
} catch (CursorIndexOutOfBoundsException e){
//...
}
}
adapter = new DiaryCursorAdapter(getContext(), data);
mListView.setAdapter(adapter);
}
}
最后,这是我的自定义适配器
public class DiaryCursorAdapter extends CursorAdapter {
Context context;
private long ident;
public DiaryCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.context = context;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ident = cursor.getLong(0);
TextView title = (TextView) view.findViewById(R.id.listitem_title);
title.setText(cursor.getString(1));
TextView location = (TextView) view.findViewById(R.id.listitem_location);
location.setText(cursor.getString(3));
TextView date = (TextView) view.findViewById(R.id.listitem_date);
date.setText(cursor.getString(4));
TextView content = (TextView) view.findViewById(R.id.listitem_content);
content.setText(cursor.getString(2));
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
return layoutInflater.inflate(R.layout.listview_diary_entries, parent, false);
//return view;
}
@Override
public long getItemId(int position) {
return ident;
}}
我尝试在没有AsyncTask的情况下填充列表视图。 顺便说一下,相应布局文件中ListView的父级是LinearLayout(不是滚动视图,因为我发现这是一个可能的问题)。
答案 0 :(得分:0)
项目ID最终将通过调用getItemId()返回,因此您重写此项以返回“ident”,它对您的CursorAdaptor类是私有的,并且将针对每一行进行更改。
您需要将您的ident更改为ident(或类似的)的ArrayList,您可以通过传递给getItemId()调用的'position'值来访问它。
答案 1 :(得分:0)
让@pskink和@karora评论答案:
我错误地覆盖了getItemID
,这导致了我上面描述的行为。
因此,删除覆盖方法确实解决了我的问题。