Home > Software engineering >  How to execute the same function in the onCreate method of all activities?
How to execute the same function in the onCreate method of all activities?

Time:01-21

What is the problem?

I want to add this custom window callback in each activity already implemented in the app, currently I need to manually modify the code of the onCreate method of each activity or make it inherit a class that already has onCreate in the desired way, but I need that this process could be performed without modifying the app's existing code, just adding some initialization.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    window.callback = CustomCallback(window.callback, this)
}

CodePudding user response:

Inside you app Application Class (you'll need to create one, if not done yet), on "onCreate" method, call

 registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

           //Code here will run for every activity

        }
 }

CodePudding user response:

You need a BaseActivity

class BaseActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
       //your code

    }

All of your activities need to extends BaseActivity

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)            
    }    
}
  •  Tags:  
  • Related