我正在尝试将ImageView放在自定义ViewGroup中。使用Eclipse中的Graphical Layout,我可以看到边界框放在我想要的位置,但是图像本身保持在父级的(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" />
...
答案 0 :(得分:0)
我在onLayout()中调用image.layout()时添加了以下内容:
image.setPadding(imgLeft, imgTop, imgRight, imgBot);
将图像定位在与Eclipse图形布局中的边界框完全相同的位置。
但是,在我的设备上启动应用时,它仍无效。