onBackPressed()无法重新加载MainActivity

时间:2015-11-16 10:29:15

标签: java android android-activity onactivityresult onbackpressed

我在SettingsActivity中执行某些操作后尝试重新加载MainActivity。 SettingsActivity中的“我的向上”按钮运行良好,并在从SettingsActivity返回时重新加载MainActivity。但是后退按钮会保存数据,但在SettingsActivity中按下时不会重新加载MainActivity。基本上我的 getSupportLoaderManager()。restartLoader() 不能用于 onBackPressed() 你知道吗? ,我该如何解决?

我的 MainActivity 类似于:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_settings:
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivityForResult(intent, SETTINGS_REQUEST_CODE);
            break;
    }
    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == SETTINGS_REQUEST_CODE && resultCode == RESULT_OK){
        getSupportLoaderManager().restartLoader(0, null, this);
    }
}

我的 SettingsActivity 类似于:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == android.R.id.home){  //WORKS GREAT
        finishSetting();
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {   //SAVES DATA BUT DOESN'T RELOAD MAINACTIVITY
    finishSetting();
    //startActivity(new Intent(this, MainActivity.class));
}

private void finishSetting(){
    if(newLanguageSelection==null || newLanguageSelection.equals(getLanguagePreference())){
        setResult(RESULT_CANCELED);
    }
    else {
        setLanguagePreference(newLanguageSelection);
        setResult(RESULT_OK);
    }
    finish();
}

3 个答案:

答案 0 :(得分:1)

From the documentation: The activity lifecycle

编辑:

当你开始第二个活动时,你的主要暂停,当按下后退按钮时,它会恢复...

SettingsActivity上,设置一个标记(例如使用SharedPreferences

SettingsActivity.onBackPressed(){
   finishSetting();
   SharedPreferences prefs= getSharedPreferences("prefs", MODE_PRIVATE);
   prefs.edit().puBoolean("isShouldReload", true).apply();
}

然后,在MainActivity.onResume

onResume(){
   SharedPreferences prefs= getSharedPreferences("prefs", MODE_PRIVATE);
   if(prefs.getBoolean("isShouldReload", false)){
      // Do your reload.
   }
}

答案 1 :(得分:1)

您应该覆盖<input type="time"以检查主要活动是否已刷新,因此每当您从设置活动恢复到主要活动时......它都会更新..

答案 2 :(得分:0)

在public void onBackPressed()方法中,只需写:

getActionBar().setDisplayHomeAsUpEnabled(true);