For recycling the views, we follow the holder set and get tag methods and need to cast every component . For avoiding noise , have to follow this pattern . This could be helpful in code seems more clean up.

[sourcecode language=”java”]
@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (convertView == null) {
// if it’s not recycled, initialize some attributes
//
LayoutInflater inflater = (LayoutInflater) m_Context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.main, null,false);
}
ImageView image=ViewHolderPattern.get(convertView,R.id.alarm_icon/*ImageView resid*/);

TextView image=ViewHolderPattern.get(convertView,R.id.title/*TextView resid*/);
return convertView;
}

//
public static class ViewHolderPattern {
// I added a generic return type to reduce the casting noise in client
// code
@SuppressWarnings("unchecked")
public static T get(View view, int resId) {

SparseArray viewHolder = (SparseArray) view.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray();
view.setTag(viewHolder);
}
View childView = viewHolder.get(resId);

if (childView == null) {
childView = view.findViewById(resId);
viewHolder.put(resId, childView);
}
return (T) childView;
}
}
[/sourcecode]

Note: Thanks to Pierre-Yves Ricau . I think this post is worth in sharing .

Avoiding the Casting noise in Adapter
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *