ListView和GridView多次调用GetView方法解决

转自:http://blog.csdn.net/u011889786/article/details/52143268

一、ListView

原因

ListView的高度不确定,一般用的是wrap_content,导致系统需要不断测量,也就多次调用onMeasure()方法,所以就多次调用getView()方法。

解决方法

把宽高写死(给个精确数字,或者match_parent)

二、GridView

原因

貌似不管长宽写不写死都是会多次调用getView。。。原因待补充

解决方法

onMeasure()调用getView的时候不要去对convertView做任何赋值的操作,只有当onLayout的时候我们再对ConvertView操作

public class MyGridView extends GridView {  
    public boolean isOnMeasure;  
    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  
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        isOnMeasure = true;  
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
    }  
  
    @Override  
    protected void onLayout(boolean changed, int l, int t, int r, int b) {  
        isOnMeasure = false;  
        super.onLayout(changed, l, t, r, b);  
    }  
}  

adapter getView();

public View getView(int position, View convertView, ViewGroup parent) {  
    System.out.println("xcqw getView  1***position"+position);  

    ViewHolder holder = null;  
    if (convertView == null) {  
        convertView = inflater.inflate(R.layout.item,  
                parent, false);  
        holder = new ViewHolder();  
        holder.tvContent = (TextView) convertView.findViewById(R.id.tv_content);  
        convertView.setTag(holder);  
    } else {  
        holder = (ViewHolder) convertView.getTag();  
    }  


    if(((MyGridView) parent).isOnMeasure){  
        //如果是onMeasure调用的就立即返回  
        return convertView;  
    }  
    System.out.println("xcqw getView  2***position"+position);  

    //如果不是onMeasure调用的就可以正常赋值操作  
    String content = contentList.get(position);  
    holder.tvContent.setText(content);  

    return convertView;  
}  

你可能感兴趣的:(ListView和GridView多次调用GetView方法解决)