AbsListView 使用的设计模式理解(一)

      AbsListView 是GridView ListView 的父类,在设计AbsListView 的时候,Android 的程序员采用了Adapter设计模式。

      Adapter英文字面意思是适配器的意思,所以Adapter设计模式的中心就是适配与转换。AbsListView设置Adapter就是采用的该模式,将数据转化为View 呈现在界面上。现就BaseAdapter分析如下:

     在继承BaseAdapter 需要实现四个方法,如下:

     public View        getView(int position, View  convertView, ViewGroup  parent)
     abstract int        getCount()
         How many items are in the data set represented by this Adapter.
   abstract Object     getItem(int position)
    Get the data item associated with the specified position in the data set.
   abstract long     getItemId(int position)
    Get the row id associated with the specified position in the list.

  前两个方法比较好理解,后两个方法比较令人费解,也比较难以理解,所以废话不多说,getItemId 这个方法是取得每个Item rowid ,注意不是position,这是因为有可能带有Header ,或者其他因素,所以在CursorAdapter中这样实现该方法,代码如下:

   public long getItemId(int position) {
        if (mDataValid && mCursor != null) {
            if (mCursor.moveToPosition(position)) {
                return mCursor.getLong(mRowIDColumn);
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }

   因为CursorAdapter是BaseAdapter绑定一个Cursor而成,所以就此可以下结论,getItemId 就想当于SQL中Table 的rowId 一样,是唯一标识一个Item的唯一Id。此外,AbsListView的setOnItemClickListener 在响应事件的时候,就是回调的getItemId 方法。public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}

  这里的Id就是通过getItemId 得到的Id

       

  

猜你喜欢

转载自blog.csdn.net/gezihau/article/details/44003539