ListView and GridView call getView multiple times, resulting in misalignment of assignment
Recently, I have always encountered errors in writing GridView adapter assignment when the last one or two need to define other pictures. The reason is that the adapter's getView is called multiple times, resulting in data assignment errors. I finally found a solution for searching online to record it.
1.ListView
1. Reason
Because listView generally uses wrap_content, which is highly uncertain, the system needs to continuously measure, so the onMeasure method is called many times, so getView is called many times.
2. Solve
It's very simple, just write down the width and height to death (clearly give a number or match_parent)
2.GridView
1. Reason
Whether the height and width are written to the dead or not, getView will be called many times, and the reasons need to be explored. . . .
2. Solve
It is impossible to prevent multiple calls to getView. You can only do not assign values to convertView when onMeasure calls getView. You can only operate on ConvertView when onLayout.
1).Custom GridView:
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; (widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { isOnMeasure = false; (changed, l, t, r, b); } }
2).The processing of ConvertView in getView
@Override public View getView(int position, View convertView, ViewGroup parent) { ("xcqw getView 1***position"+position); ViewHolder holder = null; if (convertView == null) { convertView = (, parent, false); holder = new ViewHolder(); = (TextView) (.tv_content); (holder); } else { holder = (ViewHolder) (); } if(((MyGridView) parent).isOnMeasure){ //If it is called onMeasure, return immediately return convertView; } ("xcqw getView 2***position"+position); String content = (position); (content); //If it is not called onMeasure, it can be operated normally //Assignment operation return convertView; }
This will be OK.
If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!