Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a method after View is created - Android

Tags:

java

android

I've currently got an activity that creates a view. this view uses other classes (such as one to create a random sequence of integers). I need to run a method (which will display the sequence using bitmaps) once the view is created. So once the user clicks "Start Game" this sequence will be displayed.

I've tried calling the method after setting the content view inside the onCreate method by the sequence is not generated (all 0's) correctly. I've tries this also with onStart and onFinishInflate inside the myView class.

Is there a way i can run this method after everything is inflated and initialized? So after the user clicks "Start Game" and the view is changed, the method needs to run.

Thanks for looking.

Edit: A failed attempt.

@Override
protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);
  this.gameView = new GameView(getApplicationContext(), getCellSource(getApplicationContext()));
  setContentView(this.gameView);
  // this.gameView.displaySequence(this.gameView.gameEngine.getGenSequence()); Need this to run once view is displayed.
}
like image 366
Waddas Avatar asked Jun 28 '26 03:06

Waddas


1 Answers

Try using ViewTreeObserver as follow:

final View yourView = View.inflate(....);
    ViewTreeObserver observer = yourView .getViewTreeObserver();

    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            // Do what you need with yourView here...

        }
    });

Notice that the function removeGlobalOnLayoutListener(this) is different in some sdk versions.

like image 143
Udi Oshi Avatar answered Jun 30 '26 18:06

Udi Oshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!