首页 > 代码库 > android中ViewHolder通用简洁写法
android中ViewHolder通用简洁写法
public class ViewHolder { // I added a generic return type to reduce the casting noise in client code @SuppressWarnings("unchecked") public static <T extends View> T get(View view, int id) { SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(); if (viewHolder == null) { viewHolder = new SparseArray<View>(); view.setTag(viewHolder); } View childView = viewHolder.get(id); if (childView == null) { childView = view.findViewById(id); viewHolder.put(id, childView); } return (T) childView; }}
使用方式如下:
@Overridepublic View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(context) .inflate(R.layout.banana_phone, parent, false); } ImageView bananaView = ViewHolder.get(convertView, R.id.banana); TextView phoneView = ViewHolder.get(convertView, R.id.phone); BananaPhone bananaPhone = getItem(position); phoneView.setText(bananaPhone.getPhone()); bananaView.setImageResource(bananaPhone.getBanana()); return convertView;}
可以将此类添加到常用类库中,一劳永逸。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。