learning target:
Understand getView
Code part:
Use Java language
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ViewHold viewHold;
//判断是否存在缓存
if (convertView == null) {
viewHold = new ViewHold();
convertView = LayoutInflater.from(content).inflate(R.layout.demo_item, viewGroup, false);
viewHold.textView = convertView.findViewById(R.id.title);
viewHold.button = convertView.findViewById(R.id.confirm);
convertView.setTag(viewHold); //将Holder存储到view中,给下次view用来复用
}else{
viewHold = (ViewHold) convertView.getTag();//复用view
}
viewHold.textView.setText(title.get(position));
return convertView;
}
class ViewHold {
TextView textView;
Button button;
}
- getView means to get the interface to be displayed for the item
parameter name | meaning |
---|---|
position | Subscript |
convertView | Available cache objects provided by the system |
viewGroup | Root object |
The purpose of judging whether the convertView is empty is to reuse objects and reduce memory overhead.
The reason that ViewHold is an internal class is because ViewHold is only used once in the adapter.
When the convertView is empty, it means that it is the first time the adapter is loaded, an object needs to be loaded, the template is loaded using the LayoutInflater method, and finally the set viewHold object is saved to the cache in the convertView with setTag, and the view is loaded next time Time reuse objects.
When the convertView is not empty, the viewHold object obtains the set viewHold object from the convertView; thereby achieving the purpose of object reuse.
viewHold.textView.setText(title.get(position));
Finally, set the desired data to the specified position.