LayoutAnimation动画
LayoutAnimation作用于ViewGroup,为ViewGroup指定一个动画,这样当它的子元素出场时,都会具有这种效果。
实例:
1.在res目录下,新建一个anim目录,在anim目录下,创建一个anim_item.xml文件,文件内容:
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:shareInterpolator="true">
<alpha
android:fromAlpha="0.0"
android:toAlpha="1.0" />
<translate
android:fromXDelta="500"
android:toXDelta="0" />
</set>
2.在anim中创建一个anim_item_layout的xml文件(这个可以不写,可以在代码中实现),内容如下:
<layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
android:animation="@anim/anim_item"
android:animationOrder="normal"
android:delay="0.3">
</layoutAnimation>
3.在activity_main.xml文件中(如果没有anim_item_layout.xml文件,在Listview可以不引用android:layoutAnimation属性)。
<RelativeLayout 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"
tools:context="www.zhang.com.layoutanimation.MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg"
android:layoutAnimation="@anim/anim_item_layout"
android:scrollbars="none" />
</RelativeLayout>
3.listview的item布局文件listview_item.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg"
android:gravity="center"
android:textSize="20sp" />
4.在MainActivity文件中
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private String [] strings = {"haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe","haha","hehe"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listview);
mListView.setAdapter(new ArrayAdapter<String>(this,R.layout.listview_item,strings));
layoutAnim();
}
private void layoutAnim() {
//加载xml动画
Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_item);
//为viewgroup的子元素设置该动画
LayoutAnimationController controller = new LayoutAnimationController(animation);
//设置延时执行时间*0.5,对应的是delay属性
controller.setDelay(0.5f);
//设置动画执行的顺序,对应的是android:animationOrder属性
controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
//将控制行为设置给viewgroup
mListView.setLayoutAnimation(controller);
}
}