I'm not an Android programmer, but, as a general advice, I'd say you should perform the sleep, better said the waiting, on another thread and execute at the end of the waiting period, on the main thread, a method that toggles the visibility of your imageview.
Getting into more specific detail, I'd say you must use a Handler object because you cannot update most UI objects while in a separate thread. When you send a message to the Handler it will get saved into a queue and get executed by the UI thread as soon as possible:
public class MyActivity extends Activity {
// Handler needed for callbacks to the UI thread
final Handler mHandler = new Handler();
// Create runnable for posting
final Runnable mUpdateUIState = new Runnable() {
public void run() {
updateUIState();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
[ . . . ]
}
protected void startToggle() {
// Fire off a thread to do the waiting
Thread t = new Thread() {
public void run() {
Thread.Sleep(5000);
mHandler.post(mUpdateUIState);
}
};
t.start();
}
private void updateUiState() {
// Back in the UI thread -- toggle imageview's visibility
imageview.setVisibility(1 - imageview.getVisibility());
}
}
or, a snippet of a shorter version,
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
imageview.setVisibility(1 - imageview.getVisibility());
}
}, 5000);
using the postDelayed
method, that incorporates the delay within the message posting logic.