public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview;
if (convertView==null){
imageview=new ImageView(MyActivity.this);
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageview.setPadding(5,0,5,0);
}else{
imageview=(ImageView)convertView;
}
imageview.setImageResource(imageId[position]);
return imageview;
}
当一张图片滑进屏幕的时候,调用这个getview()
?那么其中第一个if条件null
是什么?如何理解这里面的条件语句?
To put it simply, it is for reuse and avoids generating a new view from the layout resource file (or generating a new view through code) every time .
For example, like
ListView
orGridView
, if N items can be displayed on the screen, thengetView
will be called N times to provide a view of the corresponding position. Reusing previously generated views can improve efficiency.Parameter description of the getView() method in the android.widget.Adapter source code file:
But you still need to check if it is empty and of the appropriate type.
This is to avoid creating duplicate objects. It is for better reuse
getView creates a view object through the adapter to fill in the listview, etc. to determine whether the convertview is cached. If it is cached, there is no need to create a new view and the purpose of reuse can be achieved. Nowadays, the getview method is generally not written like this. There is a more efficient way to write it. It has been too long since I wrote about Android