ListView重用视图时,我不希望它
我有一个ListView ,其中每个item包含一个ToggleButton 。 当我切换它,然后向上或向下滚动,ListView正在回收视图,所以其他一些镜像ToggleButton的选中状态。 我不想要这个 我怎样才能防止它? 
Android为性能目的回收列表项目。 如果您希望ListView顺利滚动,强烈build议重复使用它们。
 对于每个列表项,调用适配器的getView函数。 在那里,你必须分配ListView所要求的项目的值。 
看看这个例子:
 @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if ( convertView == null ) { /* There is no view at this position, we create a new one. In this case by inflating an xml layout */ convertView = mInflater.inflate(R.layout.listview_item, null); holder = new ViewHolder(); holder.toggleOk = (ToggleButton) convertView.findViewById( R.id.togOk ); convertView.setTag (holder); } else { /* We recycle a View that already exists */ holder = (ViewHolder) convertView.getTag (); } // Once we have a reference to the View we are returning, we set its values. // Here is where you should set the ToggleButton value for this item!!! holder.toggleOk.setChecked( mToggles.get( position ) ); return convertView; } 
 请注意, ViewHolder是一个静态类,我们用它来回收视图。 它的属性是你的列表项目的意见。 它在你的适配器中声明。 
 static class ViewHolder{ ToggleButton toggleOk; } 
  mToggles在你的适配器中被声明为一个私有属性,并用这样的公共方法设置: 
 public void setToggleList( ArrayList<Boolean> list ){ this.mToggles = list; notifyDataSetChanged(); } 
查看其他自定义ListView示例以获取更多信息。
希望它有帮助。
将这两种方法添加到您的适配器。
 @Override public int getViewTypeCount() { return getCount(); } @Override public int getItemViewType(int position) { return position; } 
 你可以使用一个HashMap来保存你的button状态: 
  private Map<Integer,Boolean> listMapBoolean = new HashMap<Integer,Boolean>(); toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { listMapBoolean.put(position, true); } else { listMapBoolean.put(position, false); } } }); 
 并在膨胀视图后,您阅读HashMap ,看看它是否被检查: 
  for (Entry<Integer, Boolean> entry : listMapBoolean.entrySet()) { if (entry.getKey().equals(i)) { if(entry.getValue()) { System.out.println("ToggleButton is checked!"); } else { System.out.println("ToggleButton is not checked!"); } } } 
 不知道这是否有助于你的方式。 我也在我的ListView回收我的EditText问题。 
可能是你应该尝试创build自己的列表视图与滚动视图和一个容器,该容器包含以编程方式添加到容器的子项。 设置识别孩子的标签,或者你可以使用孩子的顺序
- 升级到Android Studio 2.0后,在Gradle构build过程中发生大量错误
- Facebook SDK 4.10上的NPE:尝试调用空对象引用上的接口方法java.lang.Object com.facebook.inject.Lazy.get()
- 当我正在进行程序配对时,如何避免或解除Android的蓝牙配对通知?
- Android Studio无法通过错误org.gradle.process.internal.ExecException进行debugging
- Android Studio中没有libs目录
- 无法更改configuration的依赖关系(启用即时运行后)
- Android获取相机位图的方向? 并旋转-90度
- dynamic资源加载Android
- 隐藏平板电脑中的系统栏