【Android個人理解(二)】從實現方法深入瞭解自訂配接器的工作過程

來源:互聯網
上載者:User

標籤:適配器   自訂   getitem   getitemid   getcount   

自訂配接器時,需要重寫BaseAdapter的getCount(),getItem(int position),getItemId(int position),getView()方法。
但是由於不瞭解每個方法在工作時發揮的作用,而不知道如何重寫四個方法。
1、由Adapter的工作原理瞭解getCount()和getView()的作用。

getCount()用來告訴系統Item的個數,也就是我們將要繪製的個數。因此我們如此重寫這個方法:
public int getCount() {
return dataList.length;
}
但當我們在Gallery如此寫的時候:
public int getCount() {
return Integer.MAX_VALUES;
}
再加入一些其他的設定,就會出現往複迴圈的效果即系統會認為我們要繪製2的31次方的Item。
getView()最重要而大家都已熟知,在此不再複述。
2、由上可知,getItem(int position)和getItemId(int position)在繪製View中不起到作用,那他們的作用是?
getItem(int position):
官方解釋是Get the data item associated with the specified position in the data set.即獲得相應資料集合中特定位置的資料項目。那麼該方法是在哪裡被調用呢?什麼時候被調用呢?
通過查看原始碼發現,getItem方法不是在Baseadapter類中被調用的,而是在Adapterview中被調用的。
adapterView類中,我們發現getItem(position)在getItemAtPosition(int position)的構建方法中起作用,返回特定位置的資料項目。如下:
public Object getItemAtPosition(int position) {
T adapter = getAdapter();
return (adapter == null || position < 0) ? null : adapter.getItem(position);
}
而getItemAtPosition的作用是在我們重寫setOnItemClickListener、setOnItemLongClickListener、setOnItemSelectedListener時,可以調用此方法來擷取當前行資料,所以不會被系統自動調取,只會由開發人員在開發時方便調用。
綜上所述:
getItem方法:獲得相應資料集合中特定位置的資料項目,主要實現getItemAtPosition(int position)方法。
getItemAtPosition(int position)方法:擷取當前行資料,主要方便開發人員在setOnItemClickListener、setOnItemLongClickListener、setOnItemSelectedListener編寫時擷取資料。
所以一般情況下,我們可以這樣寫:
public Object getItem(int position) {
return this.datalist.get(position);
}

getItemId(int position):
返回的是該postion對應item的id,同getItem一樣,主要在含有id參數的OnClik方法中放回id的值。
所以一般情況下,我們可以這樣寫:
public long getItemId(int position) {
return position;
}
最後總結自訂配接器的步驟:
聲明適配器串連的資料
根據各自的作用實現四個方法,其中在getView中返回View對象。

補充:
getView中convertView的含義是當ListView滑動的過程中 會有item被滑出螢幕 而不再被使用 這時候Android會回收這個條目的view 這個view也就是這裡的convertView,作用是回收使用廢棄的View對象,減少View對象的初始化的次數。因此我們常常:
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView != null) {
view = convertView;
}
}

【Android個人理解(二)】從實現方法深入瞭解自訂配接器的工作過程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.