android ViewHolder模式超简洁写法
来源:互联网 发布:java 网络编程源码 编辑:程序博客网 时间:2024/06/06 18:28
- ViewHolder holder = null;
- if(convertView == null){
- convertView = mInflater.inflate(R.layout.xxx null);
- holder = new ViewHolder();
- holder.tvXXX = (TextView)findViewById(R.id.xxx);
- //...一连串的findViewById
- }
- else{
- holder = (ViewHolder) convertView.getTag();
- }
- private static class ViewHolder{
- TextView tvXXX;
- //很多view的定义
- }
这么写一次还行,但问题是总有很多很多的ViewAdapter要这么写,每次都repeat,repeat,repeat 累啊。 所以,有这么一种简洁的写法分享给大家,先声明,从国外网站上看的,不是自己原创的,但确实很喜欢这个简洁的设计。
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;
- }
- }
- @Override
- public 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;
- }
值得注意的是SparseArray这个知识点,优化过的存储integer和object键值对的hashmap,网上资料很多这里就不废话了~
来自:http://www.eoeandroid.com/thread-321547-1-1.html
0 0
- android ViewHolder模式超简洁写法
- Android ViewHolder模式超简洁写法
- android ViewHolder模式超简洁写法
- android ViewHolder模式超简洁写法
- android ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- ViewHolder模式超简洁写法
- 深入理解Java的接口和抽象类
- 【LCT】BZOJ 2631:tree
- SCOI2015 day1
- [poj3264] Balanced Lineup(st表)
- UVa 796 Critical Links(无向图求割边)
- android ViewHolder模式超简洁写法
- u-boot移植之mmc,网卡配置
- ultraedit 激活办法
- echarts 百度开源图标工具demo
- 请慎用java的File#renameTo(File)方法
- 安卓开发——自定义ViewGroup
- 关于创建spring源码环境时遇到的缺少spring-cglib-repack-3.2.0.jar和spring-objenesis-repack-2.2.jar两个包的问题
- android dip、px(像素)互转
- ORA-01031: insufficient privileges