1. 程式人生 > >android GridView兩行水平滾動實現效果

android GridView兩行水平滾動實現效果

專案中要求實現兩行的水平滾動效果,當時想了很久是用listview實現呢還是用gridview實現,最後決定用gridview實現,如下:

首先重寫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); // TODO 自動生成的建構函式存根 } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO 自動生成的方法存根 int expandSpec = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE
>> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
然後在xml佈局中:
<HorizontalScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
>
    <LinearLayout
android:id=
"@+id/linearLayout1" android:layout_marginTop="20dp" android:layout_marginBottom="20dp" android:layout_width="match_parent" android:layout_height="wrap_content" > <com.xxx.MyGridView android:id="@+id/gridView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:verticalSpacing="10dp" android:stretchMode="columnWidth" > </com.xxx.MyGridView> </LinearLayout> </HorizontalScrollView>

在程式碼中這樣:

homeReqAdapter.updata(context, typeBean.data);//這是我定義的adapter載入資料,
int count = homeReqAdapter.getCount();
int columns = (count % 2 == 0) ? count / 2 : count / 2 + 1;
gridView1.setAdapter(homeReqAdapter);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columns * dm.widthPixels / NUM,
        LinearLayout.LayoutParams.WRAP_CONTENT);
gridView1.setLayoutParams(params);
gridView1.setColumnWidth(dm.widthPixels / NUM);
gridView1.setStretchMode(GridView.NO_STRETCH);
if (count <= 3) {
    gridView1.setNumColumns(count);
} else {
    gridView1.setNumColumns(columns);
}

實現上面的就可以了!主要的程式碼都在這裡了,小細節都需要自己去完善!

效果圖如下: