[英]Android - animate an image without setting an imageView
在我的應用中,我想為從一側流入而另一側流出的圖像設置動畫。 我曾經像下面的代碼那樣對背景進行動畫處理,但是在那種方法中,我在activity_main
設置了一個imageView,當將動畫圖像設置在屏幕之外時,我不知道將imageView放在哪里:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView backgroundOne = (ImageView) findViewById(R.id.background_one);
final ImageView backgroundTwo = (ImageView) findViewById(R.id.background_two);
final ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setInterpolator(new LinearInterpolator());
animator.setDuration(10000L);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
final float progress = (float) animation.getAnimatedValue();
final float width = backgroundOne.getWidth();
final float translationX = width * progress;
backgroundOne.setTranslationX(translationX);
backgroundTwo.setTranslationX(translationX - width);
}
});
animator.start();
}
}
使用動態插入的圖像(image_layout.xml)創建單獨的布局:
<ImageView
android:id="@+id/anim_image"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="..."/>
接下來,使用“充氣機”:
ViewGroup mainLayout = (ViewGroup) findViewById(R.id.main);
v = (ViewGroup) getLayoutInflater().inflate(R.layout.image_layout, mainLayout, false);
mainLayout.addView(v);
final ImageView backgroundOne = (ImageView) v.findViewById(R.id.anim_image);
完成:
ViewGroup mainLayout = (ViewGroup) findViewById(R.id.main);
v = (ViewGroup) getLayoutInflater().inflate(R.layout.image_layout, mainLayout, false);
mainLayout.addView(v);
final ImageView backgroundOne = (ImageView) v.findViewById(R.id.anim_image);
final ValueAnimator animator = ValueAnimator.ofFloat(1.0f, 0.0f);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setInterpolator(new LinearInterpolator());
animator.setDuration(10000L);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
final float progress = (float) animation.getAnimatedValue();
final float width = v.getWidth();
final float translationX = width * progress;
v.setTranslationX(translationX);
v.setTranslationX(translationX - width);
}
});
animator.start();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.