Avoiding the Casting noise in Adapter


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.

@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;
 }
}

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

Advertisements