2015-06-15 72 views
0

這是我的代碼。如何獲取GridView中項目的寬度和高度

@Override 
public View getView(final int position, View view, ViewGroup viewGroup) { 
    View v = view; 
    final ViewHolder viewHolder; 
    final String typeName; 

if (v == null) { 
    v = inflater.inflate(R.layout.gridview_item, viewGroup, false); 
    viewHolder = new ViewHolder(); 

    viewHolder.mView = v.findViewById(R.id.parentLayout); 
    viewHolder.picture = (ImageView) v.findViewById(R.id.picture); 
    viewHolder.name = (TextView) v.findViewById(R.id.text); 

    v.setTag(viewHolder); 

} else { 
    viewHolder = (ViewHolder) v.getTag(); 
} 

item = (ResourcesDrawables) getItem(position); 

    int width = viewHolder.mView.getWidth(); 
    int height = viewHolder.mView.getHeight(); 

我試着得到寬度/高度,但它返回0,我怎樣才能得到該項目的寬度和高度?

回答

2

如果將其放入getView()方法中,則無法正確獲取gridview單元格的高度和寬度。您正在嘗試在其繪製之前測量視圖。將其放入onMeasure()onSizeChanged()或嘗試執行onGlobalLayoutListener()。你最好的選擇就是其中之一。這個答案在這裏:Making GridView items square應該可以幫到你