[英]Animate button move and set new position in Android
我有一個ImageButton,我想在按下時移動,當動畫結束時,我希望這個按鈕在新位置停止。
這是按鈕代碼:
<ImageButton
android:id="@+id/move_button"
android:layout_width="120dp"
android:layout_height="35dp"
android:layout_centerInParent="true"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:scaleType="fitCenter"
android:background="@drawable/background_button"
android:src="@drawable/move_button"
android:onClick="MoveButton" />
我在這個網站上找到了一個代碼:
public void MoveButton(final View view) {
TranslateAnimation anim = new TranslateAnimation(0, 0, 100, 0);
anim.setDuration(300);
anim.setAnimationListener(new TranslateAnimation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation)
{
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
params.topMargin += -100;
view.setLayoutParams(params);
}
});
view.startAnimation(anim);
}
按下按鈕時,它會啟動動畫,但是當動畫完成時,按鈕返回初始位置並且應用程序崩潰。
可能是什么問題?
這是絕對的工作。
Button im= (Button) findViewById(R.id.button);
//set position TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta
final Animation animation = new TranslateAnimation(0,100,0,0);
// set Animation for 5 sec
animation.setDuration(5000);
//for button stops in the new position.
animation.setFillAfter(true);
im.startAnimation(animation);
使用anim.setFillAfter(true)
將View
放置在Animation結束的位置。
更重要的是你在Y坐標中將ImageButton
動畫從100設置為0,這就是為什么你的ImageButton
到達初始位置,因為0是它的初始位置。
嘗試下面在此代碼我用代碼anim.setFillAfter(true)
和動畫 ImageButton
Y中從0到100的坐標。
public void MoveButton(final View view) {
TranslateAnimation anim = new TranslateAnimation(0,0,0,100);
anim.setDuration(300);
anim.setFillAfter(true);
anim.setAnimationListener(new TranslateAnimation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
});
view.startAnimation(anim);
}
如果這對您有幫助,請告訴我。
使用ObjectAnimator
ObjectAnimator animation = ObjectAnimator.ofFloat(YOUR_VIEW, "translationX", 100f);
animation.setDuration(2000);
animation.start();
此代碼將在2秒內將View
100像素向右移動。
如果您需要更多信息,請轉到“ 開發人員指南”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.