我有一个应用程序,其中我使用适配器类在 3x3 GridView 中显示九个视图。在 GridView 的单元格中包含的九个视图中的每一个中,我使用 Canvas 和 Paint 对象来显示二维线图形;这些线图随后通过调用每个视图的 invalidate() 方法进行修改和重新显示。
当在 Adapter 类的重写 getView() 方法中创建视图时,所有九个视图中的线图都正确显示,但是当我尝试修改并随后重新显示线图时,除了第一个视图之外,所有视图都成功刷新网格左上角的视图,它继续显示原始线条图。我已经通过我的代码来确定第一个视图肯定是无效的,而且确实如此,所以我很困惑为什么在第一个视图上调用 invalidate() 方法不会导致它被重绘,而对所有剩余视图的相同调用会导致它们成功重绘。我还记录了对视图的 onDraw 方法的调用,这表明每次都会调用第一个视图的 onDraw 方法,所以我很确定这个问题不是由应用程序代码中的任何错误引起的。
修改和刷新九个视图的代码如下:
void updateViews(int parentTestCanvas) {
TestCanvasView testCanvas = testCanvass[parentTestCanvas];
double[] parentGenome = testCanvas.getGenome();
// Assign the parent genome to the testCanvass in the array
// The inherited genome will be subject to mutation in all cases except the first testCanvas
for(int testCanvasItem = 0; testCanvasItem < TestCanvasApp.geneCount; testCanvasItem++) {
testCanvas = testCanvass[testCanvasItem];
testCanvas.setGenome(parentGenome);
// Invalidate the testCanvas view to force it to be redrawn using the new genome
testCanvas.invalidate();
}
}
TestCanvasView类中的onDraw方法如下:
protected void onDraw(Canvas canvas) {
float xOrigin = getMeasuredWidth() / 2;
float yOrigin = getMeasuredHeight() / 2;
canvas.drawPaint(cellPaint);
canvas.translate(xOrigin, yOrigin);
drawBranch(canvas, linePaint, 0, 0, this.length, this.direction, this.xInc, this.yInc, this.scale);
Log.d("TestCanvasView", "Drawing testCanvas " + mCellIndex);
}
private void drawBranch(Canvas canvas, Paint linePaint, double startX,
double startY, double branchLen, int branchDir, double[] xInc,
double[] yInc, double scale) {
branchDir = (branchDir + 8) % 8;
double newX = startX + branchLen * xInc[branchDir];
double newY = startY + branchLen * yInc[branchDir];
canvas.drawLine((float) (startX / scale), (float) (-startY / scale),
(float) (newX / scale), (float) (-newY / scale), linePaint);
if (branchLen > 1) {
drawBranch(canvas, linePaint, newX, newY, branchLen - 1, branchDir + 1, xInc, yInc, scale);
drawBranch(canvas, linePaint, newX, newY, branchLen - 1, branchDir - 1, xInc, yInc, scale);
}
}
任何人都知道为什么第一个视图没有被重绘?