2016注定是收获成功和喜悦的一年,在接下来的一年当中应该更加努力,作一个热衷技术,热爱生活的人! java
编程不单单会是的个人职业,更多的是一种爱好, 开源会使这个行业更增强大, 自由和创新永远是主旋律. git
以前在使用TED演讲安卓客户端的时候, 做为一个将来的安卓开发者的我,看到了它的listview,因而想到了我应该怎么去实现它呢,而后昨天就抽了点时间写了个小DEMO,放到了github上, 欢迎你们观看, 今天主要是记录一下昨天我想办法实现这个效果的过程.. github
因为每一个item是在状态有不可见到可见的时候执行动画的, 那么我最初的想法就是在重写listview,在listview中监听每一个item的状态, 而后判断是否执行动画, 在listview中拿到adapter的实例, 经过adapter的实例, 得到每一个item的View ,而后设置动画集合, 可是在getAdapter().getView的时候出现问题, convertView的参数遇到问题, 不知道怎么解决, 而后发现多是思路和方向走偏了, 就又想到了去利用adapter, 在adapter中, getView方法是在每一个item变为可见状态的时候执行的, 那么这个地方正好知足个人条件,因而就在getView的时候为convertView设置了动画并执行,代码以下, 编程
public View getView(int position, View convertView, ViewGroup parent) { convertView = LayoutInflater.from(mActivity).inflate(R.layout.list_item, null); TextView textView = (TextView) convertView.findViewById(R.id.tv); String s = list.get(position).toString(); textView.setText(s); AnimationSet set = new AnimationSet(false); ScaleAnimation scale = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scale.setDuration(800); scale.setFillAfter(true); AlphaAnimation alpha = new AlphaAnimation(0.6f, 1); alpha.setDuration(1000); alpha.setFillAfter(true); set.addAnimation(scale); set.addAnimation(alpha); convertView.startAnimation(set); return convertView; }
而后,今天想到了一点点的优化, 使用了ViewHolder减小了findViewByid的次数, 因为按上述的写法的话,每一个item每次加载View的时候都得构造动画, 浪费了浪费了空间和时间, 后面将set动画集合保存到静态类ViewHolder中,大大减小了内存分配的次数,代码以下,优化从每个细节入手; 优化
public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if(convertView == null){ holder = new ViewHolder(); convertView = LayoutInflater.from(mActivity).inflate(R.layout.list_item, null); holder.textView = (TextView) convertView.findViewById(R.id.tv); AnimationSet set = new AnimationSet(false); ScaleAnimation scale = new ScaleAnimation(0.5f, 1, 0.5f, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); scale.setDuration(800); scale.setFillAfter(true); AlphaAnimation alpha = new AlphaAnimation(0.6f, 1); alpha.setDuration(1000); alpha.setFillAfter(true); set.addAnimation(scale); set.addAnimation(alpha); holder.set = set; convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } String s = list.get(position).toString(); holder.textView.setText(s); convertView.startAnimation(holder.set); return convertView; } private static class ViewHolder{ TextView textView; AnimationSet set; }
最后,祝你们2016事事顺利,收获成功! 动画