为ListView显示增加动画效果
xml方法与在java代码中实现(在代码中实现比较方便,属性见第二种方法)
1.在布局文件中创建ListView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn" android:text="开启ListView" /> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/list" android:layoutAnimation="@anim/list_anim_layout" /> </LinearLayout>
说明:List的子条目能有动画效果,主要是这句代码:layoutAnimation,
2.在res/anim文件夹中创建一个新文件,名为list_anim_layout.xml文件 作为上面ListView所指定的布局动画
<?xml version="1.0" encoding="utf-8"?> <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android" android:delay="0.5" android:animationOrder="random" android:animation="@anim/list_item"> <!-- 0.5代表延迟0.5秒后再执行下一个动画(list的item) --> </layoutAnimation>
说明:animation里的引用代表ListView子条目出现的动画效果 animationOrder中的random代表子条目出现的顺序为随机出现
3.在res/anim文件夹中创建一个新文件为子条目创建动画效果:list_item.xml 作为上面LayoutAnimation所指的动画效果
<?xml version="1.0" encoding="utf-8"?> <alpha xmlns:android="http://schemas.android.com/apk/res/android" android:fromAlpha="0" android:toAlpha="1" android:duration="2000"> </alpha>
说明:也可以用set 就可以创建多个效果 上面效果表示从透明到不透明 在2秒中完成
4.在java代码中使用ListView
public class MainActivity3 extends Activity{ private Button btn; private ListView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_layout); list = (ListView) findViewById(R.id.list); btn = (Button) findViewById(R.id.btn); ArrayList<String> arraylist=new ArrayList<String>(); arraylist.add("张山"); arraylist.add("李四"); arraylist.add("王五"); final ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arraylist); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { list.setAdapter(adapter); } }); } }
说明:只是在按钮的单击事件中添加适配器而已
以上是在xml文件中实现的,下面介绍在java代码中怎么为listView设置动画
在代码中使用LayoutAnimationController为ListView设置动画的步骤:
1.创建一个Animation对象:
可以通过xml文件或者直接使用Animation的构造函数创建Animation对象
2.使用如下代码创建LayoutAnimationController对象:
LayoutAnimationController lac=new LayoutAnimationController(animation);
3.设置控件显示的顺序:
lac.setOrder(LayoutAnimationController.ORDER_NORMAL);//ORDER_RANDOM(随机),ORDER_REVERSE(反向显示) ORDER_NORMAL(正序显示)
4.为ListView设置LayoutAnimationController属性:
listView.setLayoutAnimation(lac);
修改上面的按钮单击事件中的代码为:
//获取动画效果 Animation animation=AnimationUtils.loadAnimation(MainActivity3.this, R.anim.list_item); LayoutAnimationController lac=new LayoutAnimationController(animation);//将动画效果添加到布局动画管理器中 lac.setOrder(LayoutAnimationController.ORDER_NORMAL);//设置显示顺序为正序显示 lac.setDelay(0.5f);//设置延迟0.5S后执行下一个list子条目的显示 list.setLayoutAnimation(lac);//将布局动画设置到ListView中 list.setAdapter(adapter);
说明:上面代码中的动画效果的xml文件为使用xml方法的文件
效果说明:张三 李四 王五 以淡出的方式一个一个的显示