简体   繁体   中英

When does image.setImageResource() set the image resource inside a function?

Goal: To click on an image in an app and get it to fade out to make a different image appear.

My Method: To make the 1st image fade away after 2000ms and AFTER THAT change the image resource of the 1st image to the 2nd image to make the 2nd image appear

I have a correct solution which was provided by my instructor, so I dont want any correct solution for this. What i want to know is why is my solution not working, ie why is setImageResource() setting the Image1 to Image 2 at the beginning despite calling it at the end

This is the fade function i have created which the image1 goes to when it is clicked

public void fade(View view){

    ImageView image1 = findViewById(R.id.image1);
    image1.animate().alpha(0f).setDuration(2000); 

    image1.setImageResource(R.drawable.cat2);
}

Actual Output: Image 1 changes to Image 2 as soon as I click it and then Image 2 fades away

Problem: Inspite of calling setImageResource() at the end of the code, it actually sets the image resource at the beginning

You are never telling image1.setImageResource(R.drawable.cat2); wait for 2000 millisecond and execute, So image2 appears as soon as you click it.

Solution: Call image1.setImageResource(R.drawable.cat2); After 2000ms

   new Handler().postDelayed(() -> {
        image1.setImageResource(R.drawable.cat2);
        }, 2000);

This may help.

The animation is asynchronous in your code - it doesn't block/wait, but starts the animation (or rather, queues the animation to be started) and then immediately executes the next line, which sets the image. If you want to update your image once the animation is complete, you can use withEndAction and supply a callback.

image1.animate()
    .alpha(0f)
    .setDuration(2000)
    .withEndAction(new Runnable() {
      @Override
      public void run() {
        image1.setImageResource(R.drawable.cat2);
      }
    })
    .start();

I think this will be help to you:

Fade In Fade Out Android Animation in Java

so use in onClickListener like this:

  image1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                image1.setVisibility(View.GONE);

                //Animation...

                image2.setVisibility(View.VISIBLE);

            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM