How to call recreate()?

霸气de小男生 提交于 2019-12-30 07:58:11

问题


I know this is probably extremely simple, but I just can not figure it out.

I'm trying to reload/recreate an activity after an action. I know I could just use:

Intent intent = getIntent();
finish();
startActivity(intent);

But in reading through answers on the site I'm told to use 'recreate()' after 11 api. Any help would be appreciated, thanks!


回答1:


While using the recreate method works by doing

this.recreate()

It was only added in API level 11. If you want to include more devices you can check the API level and implement both the recreate method as well as

Intent intent = getIntent();
finish();
startActivity(intent);

You can use both by making an if statement like...

if (android.os.Build.VERSION.SDK_INT >= 11) {
    //Code for recreate
    recreate();
} else {
    //Code for Intent
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}



回答2:


this.recreate() is all it takes. Stick that code inside a method that lives in the activity you want to reload. I have a project where this is tied to a button click but you can use it however you need to.




回答3:


I'm a bit confused by your question, you yourself answered the question in your answer. Call the method recreate directly...

From the documentation for recreate():

Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle to onDestroy() and a new instance then created after it.

Call recreate() from within the activity code instead of

Intent intent = getIntent();
finish();
startActivity(intent);

to restart the activity (after API 11 that is).

See this answer for a more generic recreate routine that works even for before API/SDK 11.



来源:https://stackoverflow.com/questions/29722839/how-to-call-recreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!