在上一篇博客我已经讲述了三种事件的实现方法,而现在我用复用方法来实现控件的自动移动,当然要实现控件的移动,先得在activity_main.xml文件中放置一个控件,此处我放置的是一个button控件
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="97dp"
android:id="@+id/button"
app:layout_constraintLeft_toLeftOf="@+id/activity_main"
tools:layout_constraintLeft_creator="0"
app:layout_constraintRight_toRightOf="@+id/activity_main"
tools:layout_constraintRight_creator="0" />
没有修改任何属性,实现的方法我放在了onCreate里,所以实现的是app启动后控件自动移动
1 protected void onCreate(Bundle savedInstanceState) { 2 super.onCreate(savedInstanceState); 3 setContentView(R.layout.activity_main); 4 5 Button button1=(Button)findViewById(R.id.button2); 6 TranslateAnimation animation=new TranslateAnimation(0,150,0,0); 7 animation.setRepeatCount(3); 8 animation.setDuration(2000); 9 button1.setAnimation(animation); 10 }
上面的是移动动画的实现代码,下面我拆开一一讲解;
Button button1=(Button)findViewById(R.id.button2);
实现的是找到控件
TranslateAnimation animation=new TranslateAnimation(a,b,c,d);
创建了一个移动事件,a指的是控件起始的x位置,b指结束 的x位置,c指起始y的位置,d指的是结束y的位置
animation.setRepeatCount(3);
上面代码中的setRepeatCount()方法设置的是循环的次数;
animation.setDuration(2000);
设置了一次移动所需的时间,以ms计,2000的时间就是2s,数字越小,移动越快