正如我们已经看到在以前经常使用的动画,可以通过Xml很容易的创建。
<xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%p" android:fromYDelta="0%p"
android:toXDelta="50%p" android:toYDelta="50%p"
android:duration="1000"
android:fillAfter="true" />
不幸的是在某些情况下,我们面临麻烦的局限性。怎么避免遇到这些局限性呢
通过一个例子:
我们将创建一个简单的动画来说明这个问题,当button被点击后,移动button从屏幕的左上角到中心,然后再次点击button,
希望button移回原来的位置,但是点击button没有效果,你试试点击原来button所在的左上角位置,button移动回起始位置,
这说明button的可点击区域没有跟着button移动。
正确的做法,我们必须计算,其中左上角的button开始位置(0,0)。获取被点击button大小,还要知道父控件宽度,高度,计算它需要
移动到那个位置(这里设置移动到中心点位置),通过代码动态的改变动画,当它到中心后,再次点击,然动画回到原位:
------------------
public class MyActivity extends Activity implements View.OnClickListener {
private Button button;
private RelativeLayout rel_layout;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
private void initView() {
button=(Button)findViewById(R.id.btn_hello);
rel_layout=(RelativeLayout)findViewById(R.id.rel_layout);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_hello:
//获取button,及父控件大小
int btnWidth=button.getWidth();
int btnHeight=button.getHeight();
int preantWidth=rel_layout.getWidth();
int preantHeight=rel_layout.getHeight();
boolean isInCenter=button.getLeft()>0;
Toast.makeText(MyActivity.this,"isInCenter:"+isInCenter,Toast.LENGTH_LONG).show();
//计算移动位置
final int fromX=isInCenter?(preantWidth-btnWidth)/2:0;
final int fromY=isInCenter?(preantHeight-btnHeight)/2:0;
final int toX=isInCenter?0:(preantWidth-btnWidth)/2;
final int toY=isInCenter?0:(preantHeight-btnHeight)/2;
TranslateAnimation moveanim=new TranslateAnimation(TranslateAnimation.ABSOLUTE,fromX,
TranslateAnimation.ABSOLUTE,toX,TranslateAnimation.ABSOLUTE,
fromY,TranslateAnimation.ABSOLUTE,toY);
moveanim.setDuration(1000);
moveanim.setFillAfter(true);
//启动不能少
button.startAnimation(moveanim);
//设置动画来回运动
setMoveAnimLinster(moveanim,fromX,fromY,toX,toY);
break;
default:
break;
}
}
private void setMoveAnimLinster(TranslateAnimation moveanim,int fromX,int fromY,final int toX,final int toY) {
moveanim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
//动画开始位置
params.leftMargin=0;
params.topMargin=0;
button.setLayoutParams(params);
}
@Override
public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.leftMargin=toX;
params.topMargin=toY;
button.setLayoutParams(params);
button.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
}