2013-10-16 62 views
1

所以我試圖創建一個棋盤遊戲令牌,並將該令牌放置在它的起點上。就在這個層面上發生的事情,它在ImageView上開始。但是,當我創建令牌並告訴它去哪裏時,它顯示在gridview下。任何想法或幫助將不勝感激!Android以編程方式在另一個ImageView上添加一個ImageView

我想它是因爲我在網格視圖內使用RelativeLayout.ALIGN_TOP,但我沒有看到替代方案。

的Java:

public void createToken(){ 
    // Let's create the missing ImageView 
    ImageView image = new ImageView(this); 

    // Now the layout parameters, these are a little tricky at first 
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(75, 75); 
    params.addRule(RelativeLayout.ALIGN_RIGHT, R.id.onetwo); 
    params.addRule(RelativeLayout.ALIGN_LEFT, R.id.onetwo); 
    params.addRule(RelativeLayout.ALIGN_TOP, R.id.onetwo); 
    params.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.onetwo); 

    image.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 
    image.setImageResource(R.drawable.robo); 

    // Let's get the root layout and add our ImageView 
    GridLayout layout = (GridLayout) findViewById(R.id.gridLayout1); 
    layout.addView(image, params); 
} 

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:id="@+id/root" > 

... 

<GridLayout 
    android:id="@+id/gridLayout1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:columnCount="3" 
    android:rowCount="5" > 

    ... 

    <ImageView 
     android:id="@+id/onetwo" 
     android:layout_width="75dp" 
     android:layout_height="75dp" 
     android:layout_columnSpan="1" 
     android:layout_rowSpan="1" 
     android:contentDescription="@string/gameboard" 
     android:gravity="center" 
     android:src="@drawable/tile" /> 

    ... 
</GridLayout> 

... 

</RelativeLayout> 

回答

1

我結束了以編程方式創建一個ImageView的,然後將其置於相對佈局內下方的Im​​ageView的頂部:

<GridLayout 
    android:id="@+id/gridLayout1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:columnCount="3" 
    android:rowCount="5" > 

    <RelativeLayout 
     android:layout_width="75dp" 
     android:layout_height="75dp" 
     android:layout_columnSpan="1" 
     android:layout_rowSpan="1" 
     android:id="@+id/LLoneone"> 

     <ImageView 
      android:id="@+id/oneone" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:contentDescription="@string/gameboard" 
      android:gravity="center" 
      android:src="@drawable/tile" /> 

    </RelativeLayout> 
1

如果要堆疊在彼此的頂部佈局元素,那麼你應該使用FrameLayout

+0

這是爲什麼.... – jcaruso

+0

閱讀的FrameLayout第一文檔:HTTP:/ /developer.android.com/reference/android/widget/FrameLayout.html 最重要的是這一行:'子視圖被繪製在一個堆棧中,最近添加的子項在頂部.'只需小心測試不同的屏幕大小它說如果你走這條路。 –

相關問題