This is a double question about using interfaces – namely onclickListener (and related) within an Activity.
- 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?
-
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 anonClickListenerto 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.