列表视图是否有行限制? 我使用一个片段来显示一个列表视图,我给它提供了32条记录,但是当我实现一个点击时,它返回它只有12行;这是点击功能:
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
SELECTED_POSITION = position;
if (listView.getChildCount() > 0) {
listView.getChildAt(position).setBackgroundColor(
Color.parseColor("#036287"));
}
}
当执行listView.getChildAt(position)并且position是一个大于11的数字时,会发生错误。同时在平板电脑上我可以看到所有行,但它们似乎与前12个记录不在同一列表视图中。
任何想法可能是什么问题?
另一个问题是,当我改变颜色时,我会看到选择了几个项目,而不是1.例如以较小的比例来解释它
-
如果最大位置为2,我选择项目1,项目1和项目3亮起。如果我选择第2项 - 第2项,第4项亮起。如果我选择第3项 - 第1项和第3项亮起,依此类推。
这真的令人沮丧,因为我无法获得我需要的视图,因为似乎有几个视图包含在该位置或列表项单击时返回的变量视图中。
答案 0 :(得分:1)
用于提供视图的数据(我猜想的List<>>假设)的大小为32,这并不意味着ListView有32个子视图。
列表视图只有足够数量的视图来填充ListView(在你的情况下恰好是11)
如果要更改视图的颜色,可以操作在侦听器中收到的“view”参数:
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick(listView, view, position, id);
view.setBackgroundColor([your color here]);
}
或者将相应的数据添加到用于提供适配器的数据模型中,然后在列表中调用notifyDataSetChanged
public void onListItemClick(ListView listView, View view, int position, long id)
{
super.onListItemClick(listView, view, position, id);
YourObject yourObject = yourObjectList.get(position);
yourObject.clicked = true;
}
然后在getView
中@Override
public View getView(int position, View convertView, ViewGroup parent)
{
[...]
YourObject yourObject = yourObjectList.get(position);
if(yourObject.clicked)
{
convertView.setBackgroundColor([your color here])
}
else
{
convertView.setBackgroundColor([your other color here])
}
}
对于你的情况,我会使用第一个选项,但是第二个ono在你没有直接引用视图的场景中很有用(比如在背景中发生的事情)
答案 1 :(得分:0)
数据可能会通过ListView
提供给您的Adapter
。出于优化目的,Listview
仅包含屏幕上当前显示的项目。渲染所有视图将浪费资源。因此,指定位置的项目可能与您单击的项目不同。
onListItemCLick
包含对作为参数使用的View对象的引用,因此我的建议是设置作为参数给出的View
的背景颜色。
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
view.setBackgroundColor(Color.parseColor("#036287"));
}
答案 2 :(得分:0)
在你的getView()方法中,只需按照这种方式尝试
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.friendName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setBackgroundColor(Color.parseColor("#D9D9D9"));
holder.text.setTextColor(Color.parseColor("#353535"));
return convertView;
}
和
class ViewHolder {
TextView text;
}