问题描述
如何重新启动Android Activity
?我尝试了以下操作,但是Activity
只是退出了.
How do I restart an Android Activity
? I tried the following, but the Activity
simply quits.
public static void restartActivity(Activity act){
Intent intent=new Intent();
intent.setClass(act, act.getClass());
act.startActivity(intent);
act.finish();
}
推荐答案
我做了这样的主题切换器:
I did my theme switcher like this:
Intent intent = getIntent();
finish();
startActivity(intent);
基本上,我首先调用finish()
,并且使用的是与开始此活动完全相同的意图.似乎可以解决问题?
Basically, I'm calling finish()
first, and I'm using the exact same intent this activity was started with. That seems to do the trick?
更新:如下面的拉尔夫(Ralf)所述, Activity.recreate()
是进入API 11及更高版本的方法.如果您使用的是API11 +环境,则更可取.如果您使用的是API 10或更低版本,您仍然可以检查当前版本并调用上面的代码段. (请不要忘记赞扬拉尔夫的答案!)
UPDATE: As pointed out by Ralf below, Activity.recreate()
is the way to go in API 11 and beyond. This is preferable if you're in an API11+ environment. You can still check the current version and call the code snippet above if you're in API 10 or below. (Please don't forget to upvote Ralf's answer!)
这篇关于如何在Android中重新启动Activity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!