如何在 Android 中重新启动 Activity [英] How to restart Activity in Android

查看:65
本文介绍了如何在 Android 中重新启动 Activity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重新启动 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 或更低版本,您仍然可以检查当前版本并调用上面的代码片段.(请不要忘记为 Ralf 的回答点赞!)

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆