• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps How to delay a switch between views

gostaf`

Lurker
Jul 10, 2009
5
0
Hi

I would like to switch between views after a certain amount of time (sort of delay). I tried doing that by using a gave timer object, but that just doesn't work (my guess is you can only switch views from the UI thread).

Can anyone give me a hint or point me to an example of how this can be done?


Doron
 
Okay.

Here's a simple solution.

Put a thread in your activity (independent class) and have it act as the timer.

Make your activity implement Runnable.

When the timer elapses, use a Handler to call the run() method of your activity. This will ensure it is running on the UI thread, and you will be able to switch views.

Here's a trivial example. I have 2 views, main and main2.

public class ViewSwitch extends Activity implements Runnable {
switcher s;
Thread th;
Handler handler = new Handler();
int whichView = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

s = new switcher(this, handler);
(th = new Thread(s)).start();
}

/**
* This class will implement the timer, calling run() on the UI thread
* each time the timer elapses.
*/
public class switcher implements Runnable {
private boolean _running = true;
private Handler _handler;
private Runnable _runnable;

public switcher(Runnable runnable, Handler handler) {
_runnable = runnable;
_handler = handler;
}

public void setRunning(boolean running) {
_running = running;
}

public void run() {
while(_running) {
try { Thread.sleep( 1000 ); } catch(InterruptedException ex) {}
if( _running ) _handler.post( _runnable );
}
}
}

/**
* Now on UI thread. Switch views.
*/
public void run() {
switch( whichView ) {
case 0:
setContentView( R.layout.main2 );
whichView = 1;
break;
case 1:
setContentView( R.layout.main );
whichView = 0;
break;
}
}
}

Scott
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones