How to move image up and down continuously using t

2019-01-17 01:21发布

问题:

I have successfully done one side animation using Translate Animation means the image goes from top to the bottom. Here is the code:

private ImageView mScanner;
private Animation mAnimation;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mScanner = (ImageView)findViewById(R.id.Scanner);

    mAnimation = new TranslateAnimation(0, 0, 0, 500);
    mAnimation.setDuration(10000);
    mAnimation.setFillAfter(true);
    mAnimation.setRepeatCount(-1);
    mAnimation.setRepeatMode(Animation.REVERSE);
    mScanner.setAnimation(mAnimation);
    mScanner.setVisibility(View.VISIBLE);
}

Now I want that when image reaches to the bottom of the screen, it should start moving back to the top. How can I do that?

Note: Done the reverse mode. Please see the code. But now problem is that, it leaves lines when moving from bottom to top. Like the attached image. How to remove this lines?

回答1:

Modify your code according to this:

   mScanner.setVisibility(View.VISIBLE);
   mAnimation = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 1.0f);
   mAnimation.setDuration(10000);
   mAnimation.setRepeatCount(-1);
   mAnimation.setRepeatMode(Animation.REVERSE);
   mAnimation.setInterpolator(new LinearInterpolator());
   mScanner.setAnimation(mAnimation);

And moreover use xml rather than image. Please see the below code and put it in your ImageView src.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <solid android:color="#0000FF"/>
    <size android:width="480dp"
        android:height="10dp"/>
    <corners android:radius="1dp"/>
    <stroke android:width="3dp"
        android:color="#000000"/>
</shape>

I hope it will help you.



回答2:

You need to set the repeat property

android:repeatMode

int. How an animation behaves when it reaches the end of the animation. android:repeatCount must be set to a positive integer or "-1" for this attribute to have an effect. Set to "reverse" to have the animation reverse direction with each iteration or "repeat" to have the animation loop from the beginning each time.

Animation a;
a.setRepeatMode(Animation.REVERSE);


回答3:

I think you have to remove mAnimation.setFillAfter(true); because this means that it will stay permanently where it stops.

In order to return to the initial position, either you can make a complete animation set for both moving up and down, or make two separate and when the first finish, then start the second, although there is no reason to follow such an approach.