首页 > 解决方案 > 关于如何让 onResume() 运行 onCreate() 代码的问题

问题描述

我是安卓新手。我有一个关于 onResume() 的问题。从第二个活动返回后,如何使我的活动在 onCreate() 中重新运行代码?(例如,我已经更新了活动 2 中的一些数据,并希望在活动 2 回来后刷新活动 1 以在 onCreate()中运行代码)无论如何更好的做法而不是重新输入onCreate() 到 onResume() 中的代码。抱歉我的英语语法不好,并提前感谢。

标签: android

解决方案


将您希望运行的部分提取到一个单独的函数中,然后在和onResume()中调用该函数。onCreate()onCreate()onResume()

protected void onCreate(Bundle b){
    //Code specific to onCreate call
    //...
    //Invoke the common function
    commonFunction();
}

protected void onResume(){
    //Invoke the common function here as well
    commonFunction();
}
private void commonFunction(){
    //piece of code you want to execute in both onCreate and onResume
    //...
}

推荐阅读