2011年10月3日 星期一

[ListView] The World of List View

[Adapters]
  • Terminology
    • index: Child views
    • position: Data in Adapter
    • id: Unique identifier for data
  • getView(int position, View convertView, ViewGroup parent)
    • Full data presentation control
    • Optimization
    • Shoot yourself in the foot (and the face) (搬起石頭砸自己的腳?)
  • convertView
    • Supplied by ListView
    • Matches item types
    • Reuse it

  • The Right Way to use getView().
    • 當 convertView 是 null 時,才 inflate layout,這樣才真正有 reuse。

public View getView(int position, View convertView, ViewGroup parent) { 
     if (convertView == null) { 
         convertView = mInflater.inflate(R.layout.item, parent, false); 
     } 
     ((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]); 
     ((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap( 
             (position & 1) == 1 ? mIcon1 : mIcon2); 
     return convertView; 
}


  • The Fast Way to use getView().
    • 將 layout 的 element 儲存在 viewHolder,共用同一份物件。
static class ViewHolder { 
        TextView text; 
        ImageView icon; 
}

  • How to shoot yourself in the foot (?)
    • Local view cache
    • Accessing views from the adapter
    • Change convertView’s structure
    • Assumptions about getView calls
  • Handling data changes
    • notifyDataSetChanged()
      • New or updated data
    • notifyDataSetInvalidated()
      • No more data available
  • Focusable
    • Do list items focus as a whole? (false)
    • Can views within list items have focus? (true)
  • Headers and footers - Scrolling
    • ListView.addHeaderView()/ListView.addFooterView()
    • Must be called before setAdapter()
    • isSelectable == Adapter.isEnabled()

[Don’t!]
  • android:layout_height=”wrap_content”
    • ListView is virtualized, remember?
    • wrap_content = “as big as my children”
    • ListView supports unevenly sized children
    • Measure thousands of children? Android framework cheats, measures only 3 children
  • ListView inside a ScrollView
    • ScrollView scrolls and ListView scrolls, who will scroll?
  • Cache views in the adapter (?)
    • Don’t outsmart ListView
      • ListView assumes ownership of views
    • Complex recycling mechanism
      • Numerous optimizations
      • Sometimes we even leave bugs there
    • Undead views is the worst case
      • View both in the recycler and on screen
  • Use a ListView when you don’t need one!
    • ListView...
      • Is for repeating, unbounded data
    • Adds (lots of) complexity



* Reference
- 2010 Google IO - The World of List View (android-world-of-listview-android.pdf)

沒有留言:

張貼留言