android的listView有滚动条时(即实际Item数比显示出来的Item数多),其点击item变色代码入下:
for(int i=0;i<parent.getCount();i++){
View v=parent.getChildAt(i);
if (position == i) {
v.setBackgroundColor(0xFFB679D4);
} else {
v.setBackgroundColor(Color.TRANSPARENT);//此行空指针错
}
}
点击时v.setBackgroundColor(Color.TRANSPARENT);报空指针错。
错误分析:因为实际Item数比显示出来的Item数多,即parent.getCount()>parent.getChildCount(),所以View v=parent.getChildAt(i);当v不在显示的view内时,得到的v为null。所以报错
尝试方法1:parent.getCount()改成parent.getChildCount(),此时出现的新问题是往下滑动时,没有点击的Item也会变色。
尝试方法2:parent.getCount()改成一个整数,该整数=parent.getChildCount(),此时没有往下滑动时正常,但是往下滑动时并不能点击变色。
尝试方法3:做分页,代价太大。所以放弃
麻烦各位给出解决方案~~困扰很久了~
for(int i=0;i<parent.getCount();i++){
View v=parent.getChildAt(i);
if (position == i) {
v.setBackgroundColor(0xFFB679D4);
} else {
v.setBackgroundColor(Color.TRANSPARENT);//此行空指针错
}
}
点击时v.setBackgroundColor(Color.TRANSPARENT);报空指针错。
错误分析:因为实际Item数比显示出来的Item数多,即parent.getCount()>parent.getChildCount(),所以View v=parent.getChildAt(i);当v不在显示的view内时,得到的v为null。所以报错
尝试方法1:parent.getCount()改成parent.getChildCount(),此时出现的新问题是往下滑动时,没有点击的Item也会变色。
尝试方法2:parent.getCount()改成一个整数,该整数=parent.getChildCount(),此时没有往下滑动时正常,但是往下滑动时并不能点击变色。
尝试方法3:做分页,代价太大。所以放弃
麻烦各位给出解决方案~~困扰很久了~
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null; convertView = super.getView(position, convertView, parent);
//点击变色
convertView.setOnClickListener(new OnClickListener(){ @Override
public void onClick(View v) {
// TODO Auto-generated method stub
//怎么写?
}
});
//改变item的高度
ViewGroup.LayoutParams params=convertView.getLayoutParams();
params.height=50;
convertView.setLayoutParams(params); return convertView;
}
请问事件怎么写?