I have an activity contains too many UI controls. I want to execute a method after make the activity visible.
An example i tried:
public class Main extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MyMethod(); } private void MyMethod(){ Toast.makeText(this, "Hi UI is fully loaded", Toast.LENGTH_SHORT).show(); } }
But in the above sample, the message shows before the activity is visible.
Is there a way to find out, if the activity is fully visible ?
onStart() When the activity enters the Started state, the system invokes this callback. The onStart() call makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive.
onDestroy: The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. Here is an example...... public void onDestroy() { super.
As onCreate() of an Activity is called only once, this is the point where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.
onStop() Counterpart to onStart() . The activity is no longer visible to the user. It's common to undo anything that was done in onStart() . onDestroy()
Move your code to onResume
@Override protected void onResume() { super.onResume(); MyMethod(); }
Check the activity lifecycle
http://developer.android.com/reference/android/app/Activity.html
protected void onResume ()
Called after onRestoreInstanceState(Bundle), onRestart(), or onPause(), for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.
Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user (for example, to resume a game).
Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.
Move the code on to onAttachedToWindow()
@Override public void onAttachedToWindow() { super.onAttachedToWindow(); Toast.makeText(this, "Hi UI is fully loaded", Toast.LENGTH_SHORT).show(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With