-1

How can i change an ImageButton image after a specified amount of time without touching it, in Android Studio?

Thanks!

Ravi
  • 881
  • 1
  • 9
  • 23

2 Answers2

1

Hey use this example with Thread:

  public class MainActivity extends AppCompatActivity {

        private ImageButton button;
        private boolean flagChange = false;
        private Activity mActivity;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            mActivity = this;
            button = findViewById(R.id.button1);


            //thread
            new Thread(new Runnable() {
                @Override
                public void run() {

                    //always run background
                    while(true){

                        SystemClock.sleep(2000);//2 seconds sleep

                        //update Android UI on Main Thread
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!flagChange) {
                                    button.setImageResource(R.drawable.ic_launcher_background);
                                    flagChange = true;
                                }else{
                                    button.setImageResource(R.drawable.ic_drop);
                                    flagChange = false;
                                }
                            }
                        });

                    }
                }
            }).start(); //start thread
}
Gustavo Mora
  • 843
  • 1
  • 7
  • 18
0

Did you write any logic ? Can help you correct your code if you have written anything.. Write a timer and change the image after the time has elapsed.

Ravi
  • 881
  • 1
  • 9
  • 23