2014-12-08 53 views
6

您好我正在開發小型Android應用程序,我想顯示簡單的gridview與一些elements.Its正常工作。唯一的問題是,即使有空間,它總是隻顯示兩列。它將屏幕平分爲2列,只顯示兩個元素。如果我將列數設置爲數字,即不是auto_fit,則顯示正確。我的代碼如下所示:Android GridView的android:numColumns =「auto_fit」總是隻創建兩列

<FrameLayout 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" 
> 
<GridView 
    android:id="@+id/gridView" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_margin="5dp" 
    android:numColumns="auto_fit" 
    android:verticalSpacing="10dp" 
    android:horizontalSpacing="10dp"> 
</GridView> 
</FrameLayout> 

和我的格子元素的樣子:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
tools:context="com.example.androidcardlayout.MainActivity" > 

<android.support.v7.widget.CardView 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/card_view" 
    android:layout_width="100dp" 
    android:layout_height="150dp" 
    card_view:cardCornerRadius="4dp"> 

    <RelativeLayout 
     android:id="@+id/cardMianRlt" 
     android:layout_width="100dp" 
     android:layout_height="150dp" 
     > 
    </RelativeLayout> 

難道我做錯了什麼?需要一些幫助。謝謝。

回答

9

看起來像自適應設置只適用於固定列寬的情況。這是在GridView的源代碼,使用了自動調整設定的唯一的地方:

private boolean determineColumns(int availableSpace) { 
    final int requestedHorizontalSpacing = mRequestedHorizontalSpacing; 
    final int stretchMode = mStretchMode; 
    final int requestedColumnWidth = mRequestedColumnWidth; 
    boolean didNotInitiallyFit = false; 

    if (mRequestedNumColumns == AUTO_FIT) { 
     if (requestedColumnWidth > 0) { 
      // Client told us to pick the number of columns 
      mNumColumns = (availableSpace + requestedHorizontalSpacing)/
        (requestedColumnWidth + requestedHorizontalSpacing); 
     } else { 
      // Just make up a number if we don't have enough info 
      mNumColumns = 2; 
     } 
    } 

這個私有函數是在度量/佈局過程調用。請注意,在自動擬合if語句中,除非requestedColumnWidth > 0,那麼您只會得到2列,這就是你所看到的。

如果一個固定的寬度是否適合你的應用程序,那麼你需要把它放在你的XML是這樣的:

<FrameLayout 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" 
    > 
    <GridView 
     android:id="@+id/gridView" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:layout_margin="5dp" 
     android:numColumns="auto_fit" 
     android:columnWidth="30dp" 
     android:verticalSpacing="10dp" 
     android:horizontalSpacing="10dp"> 
    </GridView> 
</FrameLayout> 
+0

確定了問題的實質和它的工作。謝謝。 – nilkash 2014-12-08 07:41:23

+0

可以分享你如何調整? – Erum 2017-09-28 11:31:06