Reputation: 123
I need to make my imageview visible after 10seconds of my buttonclick action. I have made my imageview invisible. But when ever I try to set it visible after a sleep(10000) of a thread my aplication crashes. How can I slove this? Please help!
Upvotes: 1
Views: 97
Reputation: 16910
This one is quite short, and will not block the app:
yourButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
yourImageView.postDelayed(new Runnable() {
@Override
public void run() {
if (yourImageView != null) {
yourImageView.setVisibility(View.VISIBLE);
}
}
}, 10000);
}
});
Some context: The postDelayed posts a message to the main thread, which will get executed over 10000 milliseconds, which is 10 seconds. When the 10 seconds elapsed, the main thread will take the message, and try to execute the runnable. It could be possible that the button does not exist anymore, because you left the screen, that's why a null-check is required.
Upvotes: 2
Reputation: 645
you cannot block your main thread for not more than 5 sec and as well as your thread too. Instead of using threads and making then to sleep, better user Timer.
class MyTimerTask extends TimerTask {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
startActivity(intent);
finish();
}
});
}
}
for more please read here
Upvotes: 0
Reputation: 1340
I think you did Thread.sleep() on main thread, this is not a right way to do it.
Instead, you could use AsyncTask or Handlers to delay the execution of some code.
button.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Thread.sleep(10000);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
yourView.setVisibility(VISIBLE);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Upvotes: 0