简体   繁体   中英

Switching Views inside a TimerTask - Android

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM