View.setVisibility中的java.util.ConcurrentModificationException

我正在实施拖放观点。 当开始拖动时,我将视图的可见性设置为INVISIBLE ,然后,如果拖动被中断 – 返回到VISIBLE

 public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { // Skipped some code boolean dragStarted = v.startDrag(data, shadowBuilder, v, 0); if (dragStarted) { v.setVisibility(View.INVISIBLE) } } } 

和:

 if (event.getAction() == DragEvent.ACTION_DRAG_ENDED) { View droppedView = (View) event.getLocalState(); droppedView.setVisibility(View.VISIBLE); } 

当“拖拽结束”事件被调用,我收到exception:

 E/AndroidRuntime(7118): FATAL EXCEPTION: main E/AndroidRuntime(7118): java.util.ConcurrentModificationException E/AndroidRuntime(7118): at java.util.HashMap$HashIterator.nextEntry(HashMap.java:792) E/AndroidRuntime(7118): at java.util.HashMap$KeyIterator.next(HashMap.java:819) E/AndroidRuntime(7118): at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1046) E/AndroidRuntime(7118): at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1048) E/AndroidRuntime(7118): at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1048) E/AndroidRuntime(7118): at android.view.ViewGroup.dispatchDragEvent(ViewGroup.java:1048) E/AndroidRuntime(7118): at android.view.ViewRootImpl.handleDragEvent(ViewRootImpl.java:3471) E/AndroidRuntime(7118): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2620) E/AndroidRuntime(7118): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime(7118): at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime(7118): at android.app.ActivityThread.main(ActivityThread.java:4575) E/AndroidRuntime(7118): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(7118): at java.lang.reflect.Method.invoke(Method.java:511) E/AndroidRuntime(7118): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) E/AndroidRuntime(7118): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) E/AndroidRuntime(7118): at dalvik.system.NativeStart.main(NativeMethod) 

为什么以及如何解决它?

Solutions Collecting From Web of "View.setVisibility中的java.util.ConcurrentModificationException"

你可以试试这个

 if (event.getAction() == DragEvent.ACTION_DRAG_ENDED) { final View droppedView = (View) event.getLocalState(); droppedView.post(new Runnable(){ @Override public void run() { droppedView.setVisibility(View.VISIBLE); } }); } 

看起来像Android本身试图访问视图状态,同时你拖动结束。

编辑

更精确的解释。 通过设置setVisibility() ,您可以包含或排除来自Android内部视图集合的视图,这些视图应该对拖动事件做出响应。 这个集合在拖动事件的分派过程中被使用,因此通过尝试设置setVisibility (换句话说,试图修改拖拽事件的监听器),导致了ConcurrentModificationException

也许这可以帮助。 这里给出的链接说:而不是DragEvent.ACTION_DRAG_ENDED使用DragEvent.ACTION_DROP