我想将我的 EditTexts 替换为在 ListView 上单击的项目。我使用光标沿着 ListView 上的项目移动。但是,即使当我单击其上的第二个项目时,第一个项目也会显示。我做错了什么?
这是我的 ListView onItemClicked 代码:
lv_people_info.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
people_info2 = new ArrayList<String>();
Cursor cursor2 = db.query(PeopleEntry.TABLE_NAME,// Table
allColumns, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null, // The sort order
null); // Limits the number of rows returned by the query
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
people_info2.add(cursor2.getString(1));
people_info2.add(cursor2.getString(2));
people_info2.add(cursor2.getString(3));
et_name.setText(people_info2.get(0));
et_amount.setText(people_info2.get(1));
et_description.setText(people_info2.get(2));
cursor2.moveToNext();
}
cursor2.close();
}
});
这是当我单击 ListView 的第二行时发生的情况:
最佳答案
I want to replace my EditTexts with the item clicked on my ListView .
嗯,这就是你应该做的,而不是使用光标。您的 ListView 已经填充了来自 Cursor 的数据。
因此,确实不需要再次查询它!
只需在 onClickListener()
中从该行接收必要的信息即可。
您可以使用ViewHolder
模式。创建名为 ViewHolder
的简单类,保留对您的名称、金额、描述字段的引用。然后在您的 newView()
方法中创建新的 ViewHolder 并使用 setTag()
将其附加到您的 View 。
在bindview()
中将数据绑定(bind)到它。然后,在 OnClickListener
中使用 view
中的 getTag()
。
你可以在这里看到很好的例子 https://developer.android.com/training/improving-layouts/smooth-scrolling.html
不要在 UI 线程中查询数据库!在OnClick方法中查询数据库是一个错误。如果读完文章后,您仍然想查询数据库,至少使用 CursorLoader
或 AsyncTask
。
关于java - 为什么我的光标在 ListView 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269875/