我创建了包含动态项目的listview,其中包含两个项目:CheckBox和TextView。当用户点击项目内的复选框时,它会更新textView的背景颜色。它工作正常,直到这个项滚出列表的用户空间的可见区域,我得到错误:com.viewactivities.AddNewPosition.changeTextColorWhenCheckBoxIsClicked(AddNewPosition.java:183)的java.lang.NullPointerException。
我还使用一种负责改变颜色的方法实现了接口。我观察过方法" changeTextColorWhenCheckBoxIsClicked"当listView中的项目不再可见时也会被触发(这里它会导致错误)。有人可以帮忙吗?
包含listview的类的代码和更改颜色的方法:
@Override
public void changeTextColorWhenCheckBoxIsClicked(int position) {
// TODO Auto-generated method stub
listView.getChildAt(position).findViewById(R.id.listViewItemText).setBackgroundColor(Color.BLUE);
}
来自listView适配器的代码:
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder = null;
globalPosition = position;
if(convertView==null){
LayoutInflater inflater = ((AddNewPosition) mContext).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent, false);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.listViewItemText);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.listViewItemCheckBox);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
listOfObjects.get(getPosition).setCheckBoxEnabled(buttonView.isChecked()); // Set the value of checkbox to maintain its state. changeTextColorWhenCheckBoxIsClicked(getPosition);
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.listViewItemText, viewHolder.text);
convertView.setTag(R.id.listViewItemCheckBox, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(listOfObjects.get(position).getTextFromListViewItemObject());
viewHolder.checkbox.setChecked(listOfObjects.get(position).getIsCheckedBoxEnabled());
//viewHolder.text.setBackgroundColor(Color.RED);
//ListViewItemObject tmpObject = listOfObjects.get(position);
//TextView listItemText = (TextView) convertView.findViewById(R.id.listViewItemText);
//CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.listViewItemCheckBox);
//checkBox.setChecked(false);
//listItemText.setText(tmpObject.getTextFromListViewItemObject());
return convertView;
}
@Override
public void changeTextColorWhenCheckBoxIsClicked(int position) {
// TODO Auto-generated method stub
((AddNewPosition) mContext).changeTextColorWhenCheckBoxIsClicked(position);
}
答案 0 :(得分:0)
ListView重用其视图,因此不使用setTag()而是使用列表来维持位置。
viewHolder.checkbox.setTag(position); // This line is important.
像这样的东西 - Android Listview Scrolling challenge for row elements