2015-02-10 208 views
1

我使用下面的代碼更改子網格佈局邊距:Android:如何在線性佈局內設置網格佈局?

GridLayout grid = (GridLayout) findViewById(R.id.grid); 
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); 
params.setMargins(15,marginTop,15,marginBottom); 
grid.setLayoutParams(params); 

我收到錯誤消息

android.widget.GridLayout $的LayoutParams不能轉換爲android.widget .LinearLayout $的LayoutParams

我的XML文件是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_gravity="center" 
    android:orientation="vertical" 
    android:background="#fff5f5f5" 
    tools:context=".LinearLayout" > 

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/grid" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_marginTop="100dp" 
     android:layout_marginBottom="100dp" 
     android:layout_marginLeft="10dp" 
     android:layout_marginRight="10dp" 
     android:layout_gravity="center" 
     android:columnCount="8" 
     android:rowCount="8" 
     android:orientation="horizontal"> 

</GridLayout> 

</LinearLayout> 

我應該改變什麼來擺脫錯誤?

回答

1

您不能將LinearLayout.LayoutParams分配給GridLayout。有關如何以編程方式調整GridLayout參數的示例,請參閱this SO answer

+0

是的。我嘗試過這一行:GridLayout.LayoutParams params = new GridLayout.LayoutParams()。相同的錯誤:( – 2015-02-10 02:41:21