旋转动画、平移动画--实现弹出菜单动画
2019-09-28 本文已影响0人
26小瑜儿
Demo--实现弹出菜单动画


[图片上传中...(image.png-52c8f1-1569158805919-0)]






运行结果:





源代码如下:
public class MainActivity extends AppCompatActivity {
private int [] resld = {R.id.iv_b,R.id.iv_c,R.id.iv_d};
private boolean isOpen = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView(){
ImageButton menu = findViewById(R.id.iv_a);
menu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//遍历数组 取出每一个按钮
for (int i = 0; i <resld.length; i++) {
//判断是打开还是关闭
if(isOpen == true){
//之前是打开现在需要关闭
close(i);
}else{
//之前是关闭 现在需要打开
open(i);
}
}
isOpen = !isOpen;
}
});
}
public void open (int i){
animate(i,true);
}
public void close (int i){
animate(i,false);
}
public void animate (int i,boolean state){
//计算评分之后的两个之间的角度
double angle = (Math.PI/(resld.length+1));
//获取id对应的控件
ImageButton ib = findViewById(resld[i]);
//计算当前控件对应的角度
double mAngle = (i+1)*angle;
//计算x距离
float x = (float)(Math.cos(mAngle)*200);
//计算y距离
float y = (float)(Math.sin(mAngle)*200);
float startx;
float tox;
float starty;
float toy;
Interpolator interpolator;
if(state == true){
startx = 0;
starty = 0;
tox = x;
toy = -y;
interpolator = new BounceInterpolator();
}else{
startx = x;
starty = -y;
tox = 0;
toy = 0;
interpolator = new AnticipateInterpolator();
}
//平移动画
TranslateAnimation tAnim = new TranslateAnimation(
startx,tox,starty,toy);
tAnim.setDuration(500);
tAnim.setInterpolator(interpolator);
//旋转动画
RotateAnimation rAnim = new RotateAnimation(0,360*3,
Animation.RELATIVE_TO_SELF,0.5f,
Animation.RELATIVE_TO_SELF,0.5f
);
rAnim.setDuration(500);
//创建一个AnimationSet集合 包裹多个动画 参数表示他的子动画是否公共一个插值器
AnimationSet set = new AnimationSet(false);
set.setFillAfter(true);//为什么会有setFillAfter 和 setFillBefore这两个方法:
// 是因为有动画链的原因,假定你有一个移动的动画紧跟一个淡出的动画,如果你不把移动的动画的setFillAfter置为true,那么移动动画结束后,View会回到原来的位置淡出,如果setFillAfter置为true, 就会在移动动画结束的位置淡出
set.addAnimation(rAnim);
set.addAnimation(tAnim);
//开始动画
ib.startAnimation(set);
}
}