我正在尝试将 ImageView 定位在自定义 ViewGroup 中。使用 Eclipse 中的图形布局,我可以看到边界框放置在我想要的位置,但图像本身停留在父级的 (0,0) 处。
我是否错过了对 ImageView 的测量或布局相关调用,或者布局定位错误?如何将图像与其布局边界分开?
这是我所描述的截图:http: //dl.dropbox.com/u/13477196/gameboard.png
以及来自 ViewGroup 的代码位:
public class GameViewGroup extends ViewGroup {
...
@Override
public void onLayout(boolean changed, int l, int t, int r, int b) {
for (int col = 0; col < COLS; ++col) {
for (int row = 0; row < ROWS; ++row) {
ImageView image = (ImageView) findViewById(pieceId[col][row]);
final Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
final int imgLeft = l + (int) board.getVertexX(col) - (bitmap.getWidth() / 2);
final int imgTop = t + (int) board.getVertexY(col, row) - (bitmap.getHeight() / 2);
final int imgRight = imgLeft + bitmap.getWidth();
final int imgBot = imgTop + bitmap.getHeight();
image.layout(imgLeft, imgTop, imgRight, imgBot);
}
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Draw the game board from cache
canvas.drawBitmap(cachedBitmap, 0, 0, null);
// Draw the pieces
for (int col = 0; col < COLS; ++col) {
for (int row = 0; row < ROWS; ++row) {
ImageView image = (ImageView) findViewById(pieceId[col][row]);
image.draw(canvas);
}
}
}
...
}
我使用 XML 将 ImageViews 附加到自定义 ViewGroup:
<?xml version="1.0" encoding="UTF-8"?>
<GameViewGroup
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/game_view"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
tools:context=".GameActivity">
<ImageView android:id="@+id/piece1"
android:src="@drawable/piece"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:contentDescription="@string/piece" />
...