Search code examples
androidandroid-preferences

onCreate is not called after switching back from preferences


My app only has two activities: main and preferences

In the PreferenceActivity (or in my case SettingsActivity), the user can change some stuff, that affects the MainActivity.

This is my SettingsActivity:

public class SettingsActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public static class SettingsFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
        @Override
        public void onCreate(final Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            return false;
        }
    }
}

Now I have two issue:

  1. When the user presses the HomeButton the main screen does not seem to call the onCreate so the changed preferences are not loaded in the main activity. What do I need to change, to tell android to call the onCreate function?
  2. Since android nougat there are these "activity-change-animations", so when switching to a new activity, the new screen kind of slides in. But when the user presses the HomeButton the expected animation would be slide out, but it is also slide in. How can I fix that?

Solution

  • Explanation for the first issue:

    There's a difference between onCreate and onResume

    onCreate: Activity launched for the first time. Here is where you may initialize your stuff.
    onResume: User returns to the activity after another activity goes to the background. (onPause is called on the other activity)

    For the second issue, try this:

    Intent intent = NavUtils.getParentActivityIntent(this);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    NavUtils.navigateUpTo(this, intent);
    

    Instead of

    NavUtils.navigateUpFromSameTask(this);