I am a supernova, so I ask this question.

I want to implement such a mechanism:

There is a button that, when clicked, the image (say, a square) moves some distance to the side. When pressed again, this image again moves the same distance in the same direction, and so on.

But I managed to implement only the first part - when I press the button again, nothing happens.

Code:

public class MainActivity extends AppCompatActivity { private AnimationDrawable mAnimationDrawable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView square = (ImageView) findViewById(R.id.square); square.setBackgroundResource(R.drawable.animationlist); mAnimationDrawable = (AnimationDrawable)square.getBackground(); final Button btnStart = (Button) findViewById(R.id.button); btnStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mAnimationDrawable.start(); } }); } 

Animation-list:

 <animation-list android:oneshot="true" xmlns:android="http://schemas.android.com/apk/res/android"> <item android:duration="30" android:drawable="@drawable/square_one" /> <item android:duration="30" android:drawable="@drawable/square_two" /> 

Thank you in advance.

    1 answer 1

    When you click on a button, you must understand how many times you poked it in the simplest case, create a Boolean variable in the activation field.

     boolean flag = true; 

    You should also have two animations: one moves to the right, the other to the left. Then in the leaflet button you need to call the corresponding animation, do not forget to invert the flag every time.

      btnStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (flag) { animationToRight.start(); } else { animationToLeft.start(); } flag = !flag; } });