ViewWrapper
This
GetLabel
If null
FindViewById
Return
GetIcon
If null
FindViewById
Return
not only holds onto the child widgets, but also lazy‑finds the child widgets. If you create a wrapper and never need a specific child, you never go through the operation for it and never have to pay for those CPU cycles.
The holder pattern also allows us to do the following:
• Consolidate all our per‑widget type casting in one place, rather than having to cast it everywhere we call
• Perhaps track other information about the row, such as state information we are not yet ready to “flush” to the underlying model
Using is a matter of creating an instance whenever we inflate a row and attaching said instance to the row via , as shown in this rewrite of :
Public class extends
Public onCreate
Super onCreate
SetContentView
SetListAdapter new IconicAdapter this
FindViewById
Private getModel
Return getListAdapter getItem
Public onListItemClick
SetText getModel
Class extends
IconicAdapter
Super
This
Public getView
Null
If null
GetLayoutInflater
Inflate null
New ViewWrapper
SetTag
Else
GetTag
GetLabel setText getModel
If getModel length
GetIcon setImageResource
Else
GetIcon setImageResource
Return
Just as we check to see if it is null in order to create the row as needed, we also pull out (or create) the corresponding row’s . Then accessing the child widgets is merely a matter of calling their associated methods on the wrapper.
Making a List…
Lists with pretty icons next to them are all fine and well. But can we create widgets whose rows contain interactive child widgets instead of just passive widgets like and ? For example, could we combine the with text in order to allow people to scroll a list of, say, songs and rate them right inside the list?
There is good news and bad news.
The good news is that interactive widgets in rows work just fine. The bad news is that it is a little tricky, specifically when it comes to taking action when the interactive widget’s state changes (e.g., a value is typed into a field). We need to store that state somewhere, since our widget will be recycled when the is scrolled. We need to be able to set the state based upon the actual word we are viewing as the is recycled, and we need to save the state when it changes so it can be restored when this particular row is scrolled back into view.
What makes this interesting is that, by default, the has absolutely no idea what model in the it is looking at. After all, the is just a widget, used in a row of a . We need to teach the rows which model they are currently displaying, so when their checkbox is checked they know which model’s state to modify.
So, let’s see how this is done, using the activity in the sample project at http://apress.com/. We’ll use the same basic classes as our previous demo–we’re showing a list of nonsense words, which you can then rate. In addition, words given a top rating will appear in all caps.
Дата добавления: 2015-05-16; просмотров: 767;