Android translate animation - постоянно перемещать Вид в новую позицию с помощью AnimationListener
У меня есть android translate Animation. У меня есть ImageView со случайным сгенерированным положением (next1, next2). Я вызываю пустоту каждые 3 секунды. Он создает новое положение вида, а затем создает анимацию и перемещает вид в позицию назначения. Анимация анимации реализована в AnimationListener. Когда анимация заканчивается, я постоянно перемещаю View на новую позицию (в OnAnimationEnd). Моя проблема заключается в том, что положение анимации не соответствует заданию layoutParams позиции. Когда анимация заканчивается, она переходит в новую позицию, которая составляет около 50-100 пикселей. Я думаю, что позиции должны быть одинаковыми, потому что я использую одинаковые значения (next1, next2) в обеих ситуациях. Пожалуйста, вы можете показать мне способ найти разрешение? ![Drawing of situation here here]()
FrameLayout.LayoutParams pozice_motyl = (FrameLayout.LayoutParams) pozadi_motyl.getLayoutParams();
TranslateAnimation anim = new TranslateAnimation(Animation.ABSOLUTE,pozice_motyl.leftMargin, Animation.ABSOLUTE, next1, Animation.ABSOLUTE, pozice_motyl.topMargin, Animation.ABSOLUTE, next2);
anim.setDuration(1000);
anim.setFillAfter(true);
anim.setFillEnabled(true);
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(100, 100);
layoutParams.leftMargin = (int)(next1);
layoutParams.topMargin = (int)(next2);
pozadi_motyl.setLayoutParams(layoutParams);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
pozadi_motyl.startAnimation(anim);
Вот XML-макет:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/pozadi0"
android:gravity="center_vertical"
android:layout_gravity="center_vertical"
android:background="@drawable/pozadi2"
>
<LinearLayout
android:id="@+id/pozadi_motyl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView android:id="@+id/obrazek_motyl"
android:src="@drawable/motyl"
android:layout_width="100dip"
android:layout_height="100dip"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:id="@+id/obrazek_pozadi0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView android:id="@+id/zaba_obrazek0"
android:src="@drawable/zaba_obrazek"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<cz.zaba.Spojnice
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
</FrameLayout>
Ответы
Ответ 1
Обычно я предпочитаю работать с deltas в переводе анимации, так как он избегает много путаницы.
Попробуйте это, посмотрите, работает ли это для вас:
TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);
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 += amountToMoveDown;
params.leftMargin += amountToMoveRight;
view.setLayoutParams(params);
}
});
view.startAnimation(anim);
Обязательно сделайте amountToMoveRight
/amountToMoveDown
final
Надеюсь, что это поможет:)
Ответ 2
Вам лучше использовать ViewPropertyAnimator. Это оживляет представление к его будущей позиции, и вам не нужно принудительно изменять параметры макета в представлении после окончания анимации. И это довольно просто.
myView.animate().x(50f).y(100f);
myView.animate().translateX(pixelInScreen)
Примечание. Этот пиксель не относится к представлению. Этот пиксель является пикселем на экране.
Ответ 3
вы можете просто сделать
myView.animate().y(0f);//to move to the top of the screen.