lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (selectedCourses.contains(courseNames.get(position))){
selectedCourses.remove(selectedCourses.lastIndexOf(courseNames.get(position)));
Toast.makeText(getApplicationContext(),
courseNames.get(position) + " removed", Toast.LENGTH_LONG)
.show();
row = view;
row.setBackgroundResource(R.drawable.charback);
System.out.println(selectedCourses);
}
else{
selectedCourses.add(courseNames.get(position));
Toast.makeText(getApplicationContext(),
courseNames.get(position) +" added", Toast.LENGTH_LONG)
.show();
row = view;
row.setBackgroundResource(R.drawable.white);
myarrayAdapter.notifyDataSetChanged();
System.out.println(selectedCourses);
}
所选项目变为白色,但是大约12个项目后期另一个随机项目变成白色就像进入视野一样?有人可以帮帮我吗?
答案 0 :(得分:0)
您的适配器中的getView
方法不会回收/重复使用提供的convertView
。
如果convertView
不为null,则表示它是一个正在重用的视图。这意味着您应该将后台资源显式设置为默认值,除非选中该项。您看到重复使用白色背景的原因是因为您不将背景重置为默认值。
类似的东西:
if (convertView != null) {
if (selectedCourses.contains(courseNames.get(position))){
convertView.setBackgroundResource(R.drawable.white);
} else {
convertView.setBackgroundResource(R.drawable.charback);
}
}
答案 1 :(得分:0)
试试这个:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
if (selectedCourses.contains(courseNames.get(position))){
selectedCourses.remove(selectedCourses.lastIndexOf(courseNames.get(position)));
Toast.makeText(getApplicationContext(),
courseNames.get(position) + " removed", Toast.LENGTH_LONG)
.show();
row = view;
row.setBackgroundResource(R.drawable.charback);
System.out.println(selectedCourses);
}
else{
selectedCourses.add(courseNames.get(position));
Toast.makeText(getApplicationContext(),
courseNames.get(position) +" added", Toast.LENGTH_LONG)
.show();
row = view;
row.setBackgroundResource(R.drawable.white);
System.out.println(selectedCourses);
}
我删除了myarrayAdapter.notifyDataSetChanged();线...
答案 2 :(得分:0)
您可以使用Holder类:
在你的适配器类中创建另一个包含组件的静态类:参见下面的代码
static class MyHolder {
TextView mTextView;
RelativeLayout lv;
ImageView imgInvite;
RelativeLayout rel_bckground;
}
之后在你的getView方法中使用它:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
holder = null;
if (row == null) {
// initialize your components
holder = new MyHolder();
holder.mImageView = (ImageView) row.findViewById(R.id.someID);
}else{
holder = (MyHolder) row.getTag();
}
}