我正在尝试使用SurfaceView绘制多个矩形。我的简单项目基于Android示例中的LunarLanding示例。
这是我的代码:
public CustomSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
objQueue = new LinkedList<CustomObject>();
..
}
// This is called from a different place, new data is sent multiple times/second
public void updateData(float width, float length) {
CustomObject myObj = new CustomObject(width, length);
Log.e(TAG, "[updateData]: " + myObj.width + " " + myObj.length);
if (objQueue == null) { // this is always null, adding object to queue is never executed
return;
}
objQueue.add(myObj);
Log.e(TAG, "[updateData]: objQueue.size(): " + objQueue.size());
}
private void doDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLACK);
canvas.drawPaint(paint);
paint.setColor(Color.RED);
LogUtils.LOGE(TAG, "[doDraw]"); // works fine until here
Iterator it = objQueue.iterator();
Log.e(TAG, "[doDraw]: queue size: " + objQueue.size()); // always = 0, object is never drawn..
while (it.hasNext()) {
CustomObject myObj = (CustomObject) it.next();
canvas.drawRect(...);
Log.e(TAG, "[doDraw]: CustomObject: " + myObj.width + " " + myObj.length);
}
}
我在代码中添加了一些注释,问题是队列始终为null,即使我在初始化视图时创建了它。 draw方法永远不会绘制矩形,因为队列始终为空。奇怪的是,数据已成功接收。
如果我将updateData更改为:
if (objQueue == null) {
objQueue = new LinkedList<CustomObject>();
}
每次创建新队列时,在draw方法中仍会打印出size = 0并且不会绘制矩形。
基本上我有一个监听器,我多次/秒地获取数据,我想在通过监听器发送的位置绘制一些简单的矩形。有什么想法吗?
修改:完整代码位于此处:https://gist.github.com/iRazvan/399fd702ae7704742198