0

我正在尝试将 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" />
...
4

1 回答 1

0

我在 onLayout() 中对 image.layout() 的调用下添加了以下内容:

image.setPadding(imgLeft, imgTop, imgRight, imgBot);

这将图像定位在与 Eclipse 图形布局中的边界框完全相同的位置。

但是,在我的设备上启动该应用程序时,它仍然无法正常工作。

于 2013-03-17T15:00:53.750 回答