I've looked around, but I'm not quite sure how this would work, and the only thread that was really close to what I'm looking for had 404'd information.
On an activity, I have four images laid out. I want them to change every 15 seconds to a different image, then I'll keep track of which image is there to let them link to another activity. I have the threads working and posting to System.out.println()
, but the UI is not changing and I'm not sure how to allow it. Here's what I have so far.
public int curImage1 = 1;
public int curImage2 = 2;
public int curImage3 = 3;
public int curImage4 = 4;
onCreate()
method:
// ...
imagesHandler = new Handler();
startImageSwapping();
Runnable swapImages = new Runnable() {
@Override
public void run() {
handleUpdates();
imagesHandler.postDelayed(swapImages, 3000);
}
};
public void handleUpdates() {
if (curImage1 == 1) {
((ImageView) findViewById(R.id.main_image_1)).setImageDrawable(
getResources().getDrawable(R.drawable.logo));
curImage1 = 5;
}
if (curImage1 == 5) {
((ImageView) findViewById(R.id.main_image_1)).setImageDrawable(
getResources().getDrawable(R.drawable.main_image_1));
curImage1 = 1;
}
System.out.println("TEST");
}
public void startImageSwapping() {
imageThreadIsRunning = true;
swapImages.run();
}
public void stopImageSwapping() {
imagesHandler.removeCallbacks(swapImages);
imageThreadIsRunning = false;
}
Current code after applying changes. Still not doing it, but want to keep this post updated for anyone else that runs into it.
Runnable swapImages = new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (curImage1 == 1) {
((ImageView) findViewById(R.id.main_image_1)).setImageDrawable(
getResources().getDrawable(R.drawable.logo));
curImage1 = 5;
}
if (curImage1 == 5) {
((ImageView) findViewById(R.id.main_image_1)).setImageDrawable(
getResources().getDrawable(R.drawable.main_image_1));
curImage1 = 1;
}
System.out.println("TEST");
}
});
imagesHandler.postDelayed(swapImages, 3000);
}
};
public void startImageSwapping() {
imageThreadIsRunning = true;
swapImages.run();
}
public void stopImageSwapping() {
imagesHandler.removeCallbacks(swapImages);
imageThreadIsRunning = false;
}
@Override
protected void onDestroy() {
stopImageSwapping();
super.onDestroy();
}
@Override
protected void onPause() {
stopImageSwapping();
super.onPause();
}
@Override
protected void onStop() {
stopImageSwapping();
super.onStop();
}
@Override
protected void onStart() {
if (!imageThreadIsRunning)
startImageSwapping();
super.onStart();
}
@Override
protected void onResume() {
if (!imageThreadIsRunning)
startImageSwapping();
super.onResume();
}