TranslateAnimation没有给出预期的结果

时间:2014-12-19 15:17:50

标签: android animation

我是Android新动画的新手,无法理解为什么下面的代码没有给出预期的结果。 从屏幕外的位置滑入后,我希望将按钮置于绝对位置(0,100):

Button gift = new Button(this);

    gift.setBackgroundColor(Color.BLACK);
    gift.setTextColor(Color.GREEN);

    gift.setGravity(Gravity.CENTER);;

    gift.setTextSize(18);

    gift.setText(NSLocalizedString("BONUS!\nYou Found A Solution\nAnd I Didn't!\n"));

    int from []= new int [2];
    from[0]=-500;from[1]=100;

    int to []= new int [2];
    to[0]=0;to[1]=100;

    RelativeLayout journals = (RelativeLayout) findViewById(R.id.main);
    journals.addView(gift);

    TranslateAnimation animation = new TranslateAnimation(
            Animation.ABSOLUTE, from[0],
            Animation.ABSOLUTE, from[1],
            Animation.ABSOLUTE, to[0],
            Animation.ABSOLUTE, to[1]
            );
    animation.setDuration(5000); // duartion in ms
    animation.setFillAfter(true);

    gift.startAnimation(animation);

enter image description here

1 个答案:

答案 0 :(得分:0)

首先,在你的布局xml文件中,使用RelativeLayout中的AbsoluteLayout将按钮放在你想要的位置(0,100)(在这里使用示例:http://www.tutorialspoint.com/android/android_absolute_layout.htm)。

然后,将按钮可见性设置为" 消失"作为布局xml中按钮的属性。

现在,执行以下操作:

在动画资源文件夹中添加一个文件,将其命名为slide_left.xml:

 <?xml version="1.0" encoding="utf-8"?>
 <set
   xmlns:android="http://schemas.android.com/apk/res/android">  
   <translate 
    android:fillAfter="false"
    android:fromXDelta="0%" 
    android:toXDelta="100%" 
    android:duration="1500"/>
 </set>

然后,将您的代码更改为:

...

// Your required button style :
Button gift = new Button(this);
gift.setBackgroundColor(Color.BLACK);
gift.setTextColor(Color.GREEN);
gift.setGravity(Gravity.CENTER);;
gift.setTextSize(18);
gift.setText(NSLocalizedString("BONUS!\nYou Found A Solution\nAnd I Didn't!\n"));
RelativeLayout journals = (RelativeLayout) findViewById(R.id.main);
journals.addView(gift);


// Add these below lines : 
Animation slideLeft = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_left);
gift.startAnimation(slideLeft);
gift.setVisibility(View.VISIBLE);
...

希望这能解决你的问题...