Quel événement Android n'est appelé qu'une fois jusqu'à la destruction de l'activité?

StackOverflow https://stackoverflow.com/questions/9027507

  •  14-11-2019
  •  | 
  •  

Question

Je cherche une seule réponse (mais je pourrais poser une question de mauvaise question)

Question- Est-ce que tout événement est appelé uniquement une fois au total jusqu'à la destruction d'une activité?

Je demande parce que lorsque mon utilisateur fait pivoter le téléphone au paysage OnCreate et OnStart sont invoqués tous les deux provoquant une recharge de sortes.

Je cherche un événement que je pourrais mettre un comportement à cela ne serait que courir 1x (jusqu'à ce que l'activité soit tuée)

Merci d'avance

Était-ce utile?

La solution

If it is specific to the Activity just check your savedInstanceState parameter in the onCreate event. If it is null, run your code, if not, your code has already been run.

Example:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if(savedInstanceState == null) {
        // Run your code
    }        
}

savedInstanceState will always be null when onCreate is run for the first time, and it will be populated thereafter.

Autres conseils

You don't really specify what you're trying to do with it, so I can't guarantee this is appropriate for your use, but Application.onCreate is only called once.

If you want to eliminate the recreation of your activity on an orientationchange you can listen for configchanges in the manifest.

    <activity
            android:name=".MyActivity"
            android:configChanges="orientation" >
    </activity>

And then you can override onConfigurationChanged like so:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged( newConfig );

    LinearLayout main = (LinearLayout) findViewById( R.id.mainLayout );
    main.requestLayout();
}

to recreate the layout so that it matches the new orientation, without recreating the entire activity.

Check http://developer.android.com/guide/topics/resources/runtime-changes.html to handle configuration changes and to maintain your huge data between them...if all you need to maintain between the configuration change is just the settings,you can use the onSavedInstanceState() and onRestoreInstanceState() callbacks and the given bundles.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top