Execute method when activity is visible to user

I have an activity that contains too many user interface controls. I want to execute a method to make an action 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 example above, the message is displayed before the action is visible.

Is there a way to find out if the activity is completely visible?

+7
android android-activity
source share
5 answers

Move your code to onResume

 @Override protected void onResume() { super.onResume(); MyMethod(); } 

Check Action Lifecycle

http://developer.android.com/reference/android/app/Activity.html

 protected void onResume () 

Called after onRestoreInstanceState (Bundle), onRestart () or onPause () so that your activity begins to interact with the user. This is a good place to start animating, opening devices with exclusive access (such as cameras), etc.

Keep in mind that onResume is not the best indicator that your activity is visible to the user; A system window, such as a key lock, may be in front. Use onWindowFocusChanged (boolean) to know exactly what your activity is visible to the user (for example, to resume the game).

Derived classes should move on to implementing the superclass of this method. If they do not, an exception will be thrown.

+16
source share

Move the code to onResume .

The system calls this method every time your activity comes to the fore, including when it is created for the first time. Read more about Pausing and resuming activities.

 @Override protected void onResume() { super.onResume(); MyMethod(); } 

More details in the Android Activity Lifecycle - what are all these methods for?

+5
source share

call MyMethod() in onResume() activity

According to the documentation onResume() Called when the action begins to interact with the user. At this stage, your activity is at the top of the action stack, while user input will work.

 protected void onResume() { super.onResume(); MyMethod(); } 
+2
source share

there is no real callback that is called; it is at this time that the activity is visible. But, as you can see in the attached figure, the onResume() method is called only when the action should be visible.

Also check out the activity lifecycle and documentation HERE

So your method should be called like this:

 @Override public void onResume() { super.onResume(); MyMethod(); } 

Picture

+1
source share
 // try this @Override public void onAttachedToWindow() { super.onAttachedToWindow(); Toast.makeText(this, "Hi UI is fully loaded", Toast.LENGTH_SHORT).show(); } 
+1
source share

All Articles