java - 为什么我的光标在 ListView 中不起作用?

标签 java android listview android-listview cursor

我想将我的 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 的第二行时发生的情况:

enter image description here

最佳答案

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方法中查询数据库是一个错误。如果读完文章后,您仍然想查询数据库,至少使用 CursorLoaderAsyncTask

关于java - 为什么我的光标在 ListView 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269875/

相关文章:

java - 缩放时 Android map V2 瓦片消失

java - 小部件和复合 Material 不会根据外壳大小调整大小

java - select 语句中出现意外标记

java - 使用 CLI 将 pdf 文件与 PDFBox 合并

java - 如何根据屏幕尺寸启动 Activity ?

android - 按下后退按钮时如何刷新 fragment ?

android - 减小图像的文件大小

java - 从 View (而不是 Activity )管理清理......单例模式的危险?

c# - 使用 WinAPI 设置 ListViewItem 的选中状态

Java/Android,是否可以获取对象的内容?