Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Interfaces and onCreate()

This is a double question about using interfaces - namely onclickListener (and related) within an Activity.

  1. onCreate should be short - so says the documentation - but if I have lots and lots of views all of which have onClickListeners it can get quite long. I'm worried this will cause the UI thread to timeout. Is this a problem?
  2. Is there a best way to use onClickListener? By which I mean, is it better for the Activity to implement onCLickListener and then have a very long onClick() method? Or do the following:

    mView.setOnClickListener(new OnClickListener(){
       ...
     });
    

for each View? Does it really make any difference?


2 Answers

  1. They mean "short" in that don't do anything that takes a long time to process in onCreate(). Anything like math computations, networks or database access, extremely large bitmaps inflations should be done in a thread. The only overhead that setting an onClickListener to a view is calling a method, setting a reference, and usually creating an object. If object creation does any of the aforementioned things, then it would be best to pre-load the object before creating it.

  2. There's no real difference. What you choose depends entirely on your implentation and coding stye. Using an anonymous object like you showed is kind of like a "set-and-forget" style way of doing it. It's suitable if the action is unique to the button. Creating a whole new class that that implements onClickListener() would be required if there needs to be a state that persists with each click. That way, you create the object once and set all the necessary views to the single object. It may also be useful to do it in that fashion if many views do the same action when clicked.

like image 68
DeeV Avatar answered Feb 25 '26 00:02

DeeV


It shouldn't bother with the loading of your activity because the code inside onClick listener is executed only when a click is made on its view.

Besides, its not a good idea to execute heavy stuff (network, database, drawable manipulation, etc.) in onCreate. In case if you really need to do such processing then off-load it to an AsyncTask which runs your code in a separate thread causing your UI (main) thread to be free.

like image 32
waqaslam Avatar answered Feb 25 '26 00:02

waqaslam



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!