【发布时间】:2013-01-03 07:47:03
【问题描述】:
有没有办法检查gridview 中的元素?
我找不到toggle() 方法或setChecked(true),我的gridview 有一个扩展BaseAdapter 的适配器,我想在检查元素时更改背景颜色(不仅仅是选中)。
我想要 ListView: GridView.setChoicheMode(MULTICHOICE) 然后 item.toggle() 或 item.setChecked(true) 并将检查状态存储到视图中。
编辑:
我添加了一个空的CheckedTextView 来存储检查状态。
但是有没有更清洁的方法来做到这一点?
编辑2 现在我可以做我想做的事了,但是当我向下滚动 gridview 然后向上滚动时,所选项目不再被选中。
boolean checked = layout.getCheckedItemPositions().get(position);
if(checked){
check.toggle();
view.setBackgroundColor(getResources().getColor(android.R.color.transparent));
}
else{
check.toggle();
view.setBackgroundColor(getResources().getColor(android.R.color.holo_green_light));
}
其中 layout 是 gridview 的布局。 我想我必须修改我的适配器的getView方法,但是这段代码不起作用:
CheckedTextView check = (CheckedTextView) layout.findViewById(R.id.txv_grid_check);
boolean checked = check.isChecked();
if(checked){
layout.setBackgroundColor(c.getResources().getColor(android.R.color.holo_green_light));
}
else{
layout.setBackgroundColor(c.getResources().getColor(android.R.color.transparent));
}
编辑 3
我认为没有办法做我想做的事(将状态存储在 CheckedTextView 元素中),因为滚动列表或网格视图时视图会被破坏并重新创建。所以我需要将项目的状态处理到适配器中。我使用了一个 int 的 HashSet 来存储检查项目的位置,并创建了一些公共方法来从 gridview 处理这个列表。 在 gridview 活动中,可以获取适配器,然后执行 myadapter.check(int position) 或 uncheck(int position)。 然后在adapter中,进入getView()方法,我们需要检查一个位置是否在列表中,并设置合适的背景颜色。
【问题讨论】:
-
使用选择器 xmls 作为背景来显示选定的按下状态。
-
在您的问题中添加更多说明。
-
@AdilSoomro 这可能是一个解决方案。现在我正在动态地做这件事
-
你想一次设置一个项目还是多个项目?
-
@Rajesh 多个项目。现在我可以做我想做的事了,但是当我滚动 gridview 时,项目的状态似乎丢失了