This is a double question about using interfaces - namely onclickListener (and related) within an Activity.
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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With