打开应用程序后,如何只重新创建一次活动?

问题描述

打开应用程序后,如何只重新创建一次活动?

我试图这样做,但是没有用。不断recreate()

refreshLang()inonCreate

private fun refreshLang() {
    PreferenceManager.getDefaultSharedPreferences(this).apply {
        val checkRun = getString("FirsTRUN","DEFAULT")
        if (checkRun == "YES") {
            PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit().putString("FirsTRUN","NO").apply()
            recreate()
        }
    }
}
在onDestroy中

SharPref.putString(“ FirsTRUN”,“ YES”)。apply()使它在下次运行时再次起作用。

解决方法

请参考:活动课 recreate()

它将创建新实例并启动新的活动生命周期。

因此,当您呼叫recreate()时,它将呼叫onCreate()并进入无穷循环。

您已经添加了一些条件来避免这种溢出。

编辑:

使用.equals代替==

if ("YES".equals(checkRun)) {
   PreferenceManager.getDefaultSharedPreferences(this@MainActivity).edit().putString("FIRSTRUN","NO").apply()
   recreate()
}

我建议您不要使用recreate()。它将调用onCreateonDestory()

请参阅下面的代码。

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        boolean recreateRequested = true;
        Intent currentIntent = getIntent();
        if (currentIntent.hasExtra("recreateRequested")){
            recreateRequested = currentIntent.getBooleanExtra("recreateRequested",true);
        }
        if (recreateRequested) {
            Intent intent = new Intent(this,MyActivity.class);
            intent.putExtra("recreateRequested",false);
            startActivity(intent);
            finish();
        }
    }
,

在您的String条件下,您无法像这样比较两个if

checkRun == "YES"

这是String的两个分开的实例,因此它们在这个意义上永远不相等(==-同一对象)

改为使用此

"YES".equals(checkRun)

equals将比较比较对象的“内容”,在String中,它将比较文本

,

使用onResume方法

 @Override
    public void onResume() {
        super.onResume();  // Always call the superclass method first
  
    }