2016-08-07 66 views
0

我有一個GridView,並設置列的數量和網格佈局的整體寬度。需要項目66dp x 66dp大小。但不知何故項目平方,但66x66較小。我忘了什麼?如何設置GridView行高?

int zz = .. // number of columns comes from outside 
gridview.setNumColumns(zz); 
LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)gridview.getLayoutParams(); 
linearParams.width=66*zz; 
gridview.setLayoutParams(linearParams); 

<GridView 
       android:id="@+id/gridView1" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:layout_margin="0dp" 
       android:columnWidth="66dp" 
       android:gravity="center" 
       android:horizontalSpacing="0dp" 
       android:scrollbarAlwaysDrawHorizontalTrack="true" 
       android:scrollbarAlwaysDrawVerticalTrack="true" 
       android:scrollbars="horizontal" 
       android:stretchMode="none" 
       android:verticalSpacing="0dp"> 

      </GridView> 

項目原型

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="66dp" android:layout_height="66dp"> 

    <ImageView 
     android:id="@+id/icon" 
     android:layout_width="66dp" 
     android:layout_height="66dp" 
     android:padding="0dp" 
     android:background="@android:color/holo_orange_light"/> 

</RelativeLayout> 

shreen拍攝

enter image description here

+0

你可以分享你的截圖,並有你測試該設備 –

+0

添加屏幕截圖,AL​​CATEL ONE TOUCH –

回答

0

你可以使用這個..

int width = 66*zz; 

view.setLayoutParams(new GridView.LayoutParams(GridView.width, YOUR_HEIGHT)); 
+0

我得到一個崩潰說:'AbsListView $ LayoutParams不能用你的方法強制轉換爲android.widget.LinearLayout $ LayoutParams'。你有什麼主意嗎? –

+0

也許,您正嘗試將線性佈局參數設置爲列表視圖。 –

0

LinearLayout.LayoutParams需要的像素值dp的不

int gridItemWithInDp = 66; 
int gridItemWithInPx = (int) (gridItemWithInDp * Resources.getSystem().getDisplayMetrics().density); 

linearParams.width=gridItemWithInPx *zz; 
gridview.setLayoutParams(linearParams); 
0

您應該從代碼或從申報到資源XML

設置GridView控件的寬度DP

從代碼:

final float density = getContext().getResources().getDisplayMetrics().density; 
int pixels = (int) ((66 * zz) * density + 0.5f); 

或XML

int pixels = getResources().getDimensionPixelSize(R.dimen.example_dimen); 

gridview.setNumColumns(zz); 
LinearLayout.LayoutParams linearParams =  (LinearLayout.LayoutParams)gridview.getLayoutParams(); 
linearParams.width=pixels; 
gridview.setLayoutParams(linearParams); 

設置項目原型的寬度和高度MATCH_PARENT

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" android:layout_height="match_parent"> 

    <ImageView 
     android:id="@+id/icon" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:padding="0dp" 
     android:background="@android:color/holo_orange_light"/> 

</RelativeLayout>