【发布时间】:2018-02-10 15:14:34
【问题描述】:
问候我的开发人员, 我正在做一个项目,其中我有一个列表视图,每个项目包含 2 个文本视图和 1 个复选框, 我的列表视图正在按我的意愿工作,除了当我以编程方式在列表视图上使用 setSelection(some_index) 时,所有在以前的 OnItemClickListener 调用上检查的 chechbox 都未选中, 我试图弄清楚为什么会这样,但到目前为止还没有运气, 我确实尝试在每次滚动后检查并更改所有复选框
for (int i = 0; i < listView.getCount(); i++) {
View mChild = listView.getChildAt(i);
View mChild1 = listView.getAdapter().getView(i, null, null);
TextView name = (TextView) mChild.findViewById(R.id.contact_name);
TextView phone = (TextView) mChild.findViewById(R.id.contact_number);
CheckBox box = (CheckBox) mChild.findViewById(R.id.contact_check);
if(contact.getName().equals(name.getText().toString()) && contact.getPhone().equals(phone.getText().toString()))
box.setChecked(true);
}
两种方法(mchild 和 mchild1)都不起作用,而且处理时间很长,因为我的列表视图可能会很长,(给或取 500 个项目) 关于这个问题的任何帮助,我已经坚持了几天,但无法提出任何可观的解决方案, 我不明白的一件事是,为什么我的 listview 数据集在滚动时发生变化,有什么帮助,有没有更简单快捷的方法来做到这一点,然后遍历 listview 的子项? 如果不是,那么为什么我的迭代逻辑不起作用 这是我的列表视图项目
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/list_view_margin_vertical"
android:layout_marginTop="@dimen/list_view_margin_vertical"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorBlack"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/contact_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/colorGrey"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" />
</LinearLayout>
<CheckBox
android:id="@+id/contact_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="false"
android:layout_gravity="center" />
</LinearLayout>
这是我的列表视图本身
<ListView
android:id="@+id/contactsListView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:divider="@color/colorAccent"
android:dividerHeight="1dp"
android:footerDividersEnabled="false" />
【问题讨论】:
-
最好使用recylerview而不是列表。与 listview 相比,Recyclerview 更高效、更方便。
-
@MohamedMohaideenAH 你能解释一下你刚才说的话吗,我听不懂
-
Recylerview 是列表视图的替代视图,用于列出大量数据。看看这个developer.android.com/guide/topics/ui/layout/recyclerview.html
标签: java android listview checkbox