看书的时候,看到给viewgroup子控件添加动画,所以就稍稍研究了一下。拿listview来说,当我们需要给listview中的item添加动画效果的时候,就需要用到
LayoutAnimationController这个类,通过名称我们就可以猜出来,该类是用于给layout添加动画的控制器。使用方式如下:
listView= (ListView) findViewById(R.id.listview); AnimationSet set=new AnimationSet(this,null); Animation animation=new AlphaAnimation(0.0f,1.0f); animation.setFillAfter(true); animation.setDuration(500); set.addAnimation(animation); animation=new RotateAnimation(0,90); animation.setFillAfter(true); animation.setDuration(500); set.addAnimation(animation); LayoutAnimationController controller=new LayoutAnimationController(set); for(int i=0;i<100;i++) { list.add(++i+""); } ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.text,list); listView.setAdapter(adapter); listView.setLayoutAnimation(controller);
当然,我发现该类在执行的时候,并不是很理想,加载动画的时候,只有首次加入该页面会加载,滚动listview的时候,并没有再次加载动画。
所以,我就想到能不能为每一个item单独加载动画啦?所以在我继续研究之后终于找到了更好的解决方式:
public View getView(int position, View convertView, ViewGroup parent) {
AnimationSet set=new AnimationSet(MainActivity.this,null);
set.setInterpolator(new CycleInterpolator(3));
Animation animation=new AlphaAnimation(0.0f,1.0f);
animation.setFillAfter(true);
animation.setDuration(500);
set.addAnimation(animation);
//animation=new RotateAnimation(0,180);
animation=new TranslateAnimation(Animation.RELATIVE_TO_SELF,0.0f,Animation.RELATIVE_TO_SELF,0.0f,
Animation.RELATIVE_TO_SELF,-2.0f,Animation.RELATIVE_TO_SELF,0.0f);
animation.setFillAfter(true);
animation.setDuration(500);
set.addAnimation(animation);
ViewHolder holder;
if(convertView==null)
{
holder=new ViewHolder();
convertView=getLayoutInflater().inflate(R.layout.list_item,null);
holder.textView= (TextView) convertView.findViewById(R.id.text);
convertView.setAnimation(set);
convertView.setTag(holder);
}else
{
holder= (ViewHolder) convertView.getTag();
}
holder.textView.setText(list.get(position));
Random ran=new Random();
int num=ran.nextInt(2);
switch (num) {
case 0:
convertView.startAnimation(set);
break;
case 1:
convertView.startAnimation(set);
break;
}
return convertView;
}
这样就可以为listview的每一个item单独加载动画了。