首頁  >  問答  >  主體

android - 如何理解BaseAdapter.getVeiw()参数convertView的null与非null

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中文网2724 天前910

全部回覆(3)我來回復

  • 巴扎黑

    巴扎黑2017-04-17 14:34:25

    簡單來說,是為了重複使用,避免每次從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.

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

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-17 14:34:25

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

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-17 14:34:25

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

    回覆
    0
  • 取消回覆