android - 如何理解BaseAdapter.getVeiw()参数convertView的null与非null
PHP中文网
PHP中文网 2017-04-17 14:32:25
0
3
904
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是什么?如何理解这里面的条件语句?

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(3)
巴扎黑

簡單來說,是為了重複使用,避免每次從layout資源檔案產生新的視圖(或透過程式碼產生新的視圖)
例如像ListViewGridView,螢幕上若能顯N個條目,那麼getView就被呼叫N次,以提供對應位置的視圖。而復用之前已經產生的視圖,可以提高效率。

android.widget.Adapter原始碼檔案中getView()方法的參數說明:

@convertView
The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using.

但你仍需要檢查它是否為空,以及類型是否適當。
洪涛

這個是為了避免創建重複的物件。是為了更好的重複使用

Ty80

getView透過適配器建立view物件填充listview等,判斷converview有沒有快取到,如果快取了,就不用建立新的view,可以達到重複使用的目的。現在一般getview這個方法不這樣寫,還有更有效率的寫法,太久沒寫安卓了

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!