我的ListView有点问题,它在OnItemLongClickListener中时既不会给我正确的位置也不会提供id。位置和ID在ListView中始终返回相同的值
ListView正确显示所有条目,但在长条目单击它时,会返回条目总数作为位置(与我单击的项无关)和所有条目的最高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如下(通过调用的AsyncTask在我的片段内OnCreateView)
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(不是滚动视图,因为我发现是一个可能的问题)。
run [this](https://pastebin.com/raw/SkAPUhuk),你在logcat上看到了什么? – pskink
@pskink我在哪里获得方法'getContentResolver'? – Andreas
将代码放置到“Activity#onCreate”中# – pskink