2013-03-15 93 views
0

我想將ImageView放置在自定義ViewGroup中。在Eclipse中使用圖形化佈局,我可以看到邊界框放置在我想要的位置,但圖像本身停留在父級的(0,0)處。自定義ViewGroup上的ImageView佈局僅移動「邊界框」,而不是圖像

我是否缺少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

我在onLayout()中調用image.layout()時添加了以下內容:

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

然後將圖像定位在與Eclipse圖形佈局中的邊界框完全相同的位置。

但是,在我的設備上啓動應用程序時,它仍然不起作用。