tags:

views:

31

answers:

3

I have the following code that responds to a button click, changes the view and then after 5 seconds switches the view back:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.menu);
    Button test = (Button)findViewById(R.id.browseLocation);
    test.setOnClickListener(testListener);
}
private TimerTask revert = new TimerTask(){
    @Override
    public void run() {
        setContentView(R.layout.menu);
    }
};
private OnClickListener testListener = new OnClickListener() {
    public void onClick(View v) {
        setContentView(R.layout.test);
        Timer tim = new Timer();
        tim.schedule(revert, 5000);
    }
};

However this code does not work. The run method of the timetask is hit but setContentView fails. I assume it has something to do with scope inside the timetask. How can I achieve the desired result?

A: 

Try yourActivityName.this.setContentView(). Do you know if revert is being called at all (i.e. using Logging)?

fredley
The above doesn't work.Yes revert is being called, I can place other code in the run method and it works.
CeejeeB
A: 

Found on another post that setContentView cannot be called from a non-UI thread.

Can achieve the desired affect using runOnUiThread, but not recommended.

CeejeeB
A: 

You will find your answer here : http://developer.android.com/resources/articles/timed-ui-updates.html

Mathieu