Home » Android » OnWindowFocusChanged and onCreate – Android

OnWindowFocusChanged and onCreate – Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am trying to setup the UI elements programatically.
I am able to setup the UI elements in onWindowFocusChanged method?
The question i want to ask is – shall i setup the UI elements in the onCreate method or on onWindowFocusChanged? The code –

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.baselayout);
}

And

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        res = getResources();
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        setUpBackgroundImage();// setting up the background image
        setUpTopMenu(); // Setting up the menu on top
        setUpLogo(); // Setting up the Logo
    }
}

Is the above approach correct?

How to&Answers:

Take note that some new devices are capable of showing multiple windows, onWindowFocusChanged() is not ideal place to initialize your layout. Use onCreate() to inflate layout and set up View variables.

Answer:

onCreate()
This is the place where you setup your UI

onWindowFocusChanged()
This is called when all your layouts or UI have been successfully loaded or created properly.