2014年1月29日 星期三

Android 開發 (二十) GridView 與scrollView共同使用

在開發專案時有些時候會需要類似下面左圖的樣式
上方是一個view ,下方是gridview,但是在滑動的時候卻是整片UI滑動,
也就是當滑動時會變成像右圖的樣式。


要實做這種view 有兩種方式
一種是在ScrollView裡面動態的將view 加入
另一種方法是使用 ScrollView裡面包含GridView

關於第一種作法,之後有空會在詳細說明
現在要介紹的是第二種方法,當我在實作這個方法時,
我天真的以為只需要在scrollview 裡面包 gridview就好了
程式碼如下


<ScrollView 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:background="#333333"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:background="#a5c9ff"
            android:gravity="center_horizontal|center_vertical"
            android:text="@string/hello_world" />

        <GridView
            android:id="@+id/gridview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:horizontalSpacing="3dp"
            android:numColumns="2"
            android:stretchMode="columnWidth"
            android:verticalSpacing="3dp" />
    </LinearLayout>

</ScrollView>

當我開開心心的將code 寫好,deploy到手機之後,
這才發現現實是殘酷的,事情永遠不是像我想得那麼簡單,
gridview只顯示出兩個item,其他的item不翼而飛。

為了要解決這個問題,就必須客製化gridview


public class MyGridView extends GridView { 
    public MyGridView(Context context) { 
        super(context); 
    } 
    public MyGridView(Context context, AttributeSet attrs) { 
        super(context, attrs); 
    } 
    public MyGridView(Context context, AttributeSet attrs, int defStyle) { 
        super(context, attrs, defStyle); 
    } 
    @Override 
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
 
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, 
                MeasureSpec.AT_MOST); 
        super.onMeasure(widthMeasureSpec, expandSpec); 
    } 
} 

在onMeasure的時候調整高度,然後更改原本的gridview改成客製化的gridview
這樣所有的問題就都解決了。

附上 sample Code

沒有留言:

張貼留言