最近在項目中需要在主頁中設置一個四宮格的頁面, 於是就使用了GrideView與BaseAdapter的組合,但是完成後它會滑動,並不是固定的,而且它也不是適應其父容器大小設置的.
要解決這個問題,我在BaseAdapter的getView中重寫了item的大小:
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
//四宮格,即兩行兩列
view = LayoutInflater.from(mContext).inflate(R.layout.gridview_item, null);
int height = viewGroup.getHeight() / 2;//item的高度
int width = viewGroup.getWidth() / 2;//item的寬度
GridView.LayoutParams params = new GridView.LayoutParams(width, height);
view.setLayoutParams(params);
}
//第一次調用getView時,parent的高度還是0,所以這裏需要判斷一下,並且重新設置,否則第一個子項顯示不出來
if(view.getHeight()==0){
GridView.LayoutParams layoutParams= (GridView.LayoutParams) view.getLayoutParams();
layoutParams.height=viewGroup.getHeight()/2;
layoutParams.width=viewGroup.getWidth()/2;
view.setLayoutParams(layoutParams);
}
......
return view;
}
然後在調用GridView是需要設置:
mGridView.setOverScrollMode(View.OVER_SCROLL_NEVER);
從而禁止其滾動超過頁外的item.
如有錯誤,歡迎大家來指正!