我花了整整一天試圖解決這個問題。我嘗試使用itertaion?同步和其他許多薩滿法,但是我一直在得到ConcurrentModificationException。這裏是代碼。ConcurrentModificationException當我試圖將項目添加到集合
package com.androidgui.test;
import java.util.ArrayList;
import java.util.ListIterator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
import android.widget.Toast;
public class CustomView extends SurfaceView implements Callback {
private UpdateThread thread;
private AButton btn;
private AWindow wnd;
private ArrayList<AControl> globalControls;
private Object sync;
public static int posX;
public static int posY;
public CustomView(Context context) {
super(context);
this.getHolder().addCallback(this);
this.LoadResourse();
sync = new Object();
this.globalControls = new ArrayList<AControl>();
btn = new AButton(10, 10,null,AControl.InterfaceImages.Button);
this.globalControls.add(btn);
wnd = new AWindow(10, 10, 200, 100, null);
this.SetDelegates();
}
private void LoadResourse()
{
AControl.InterfaceImages.Button = BitmapFactory.decodeResource(getResources(), R.drawable.button);
}
private void SetDelegates()
{
btn.setEventHandler(new EventHandler() {
@Override
public void ProcessEvent() {
synchronized (sync) {
globalControls.add(wnd);
}
}
});
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh)
{
posX = (this.getWidth()- AControl.InterfaceImages.Button.getWidth()) /2;
posY = (this.getHeight()- AControl.InterfaceImages.Button.getHeight()) /2;
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
thread = new UpdateThread(this.getHolder(), this);
thread.setRunning(true);
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
thread.setRunning(false);
boolean _retry=true;
try
{
while(_retry)
{
thread.join();
_retry=false;
}
}catch(Exception ex)
{
}
}
public boolean onTouchEvent(MotionEvent event)
{
synchronized (sync) {
for(AControl item :this.globalControls)
item.onClick(event);
}
return true;
}
public void onDraw(Canvas canvas)
{
synchronized (sync) {
ArrayList<AControl> temp = (ArrayList<AControl>) this.globalControls.clone();
for(AControl item :temp)
item.onDraw(canvas);
}
}
}