I just have a quick question and that is why can't I set the callback method directly in setOnClickListener() but instead I have to set a class that implements onClickListener? by saying something like setOnClickListener(new onClickListener(){}) In this case I have to set an anonymous class that implements onClickListener.
Asked
Active
Viewed 31 times
0
-
1because you cannot pass methods as arguements in java – Breavyn Nov 16 '15 at 01:23
-
Thanks for answering, but I am new to java so can you be a little bit more specific to why that is? – AnotherRandomUser Nov 16 '15 at 01:26
-
http://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java – Breavyn Nov 16 '15 at 01:27
-
Hey thanks for the link it sorta help, but in the link it doesn't describe why I can't use a method as an arguments. So I still don't understand – AnotherRandomUser Nov 16 '15 at 01:43
-
Because java is strictly an OOP language, passing functions as parameter is not an OOP concept, hence it is not allowed in the language. – Breavyn Nov 16 '15 at 01:46
-
@ColinGillespie true for android java, not so much for desktop http://stackoverflow.com/a/31685857 – zapl Nov 16 '15 at 01:47
-
Oh so that is the reason why you have to use a class containing the method as an argument but when you pass in a class like that how can the method get invoked? Don't class acts like a blue print and I have to create instance of that class and invoke the method of that instance? – AnotherRandomUser Nov 16 '15 at 01:50
-
You aren't passing in a class, you are passing an object, which is an already instantiated class. You can then access its methods same as any other object. – Breavyn Nov 16 '15 at 01:53
-
Oh ok that makes sense but I am just passing in an object without invoking the method so how does android knows to access the method when a button let say is press? – AnotherRandomUser Nov 16 '15 at 01:54
-
No, every version of java allows this. The only difference is the new Java 8 allows a few new things such as lambdas. Android allows only Java 6 and Java 7 – Breavyn Nov 16 '15 at 01:56
-
Oh ok that makes sense but I am just passing in an object without invoking the method because I when declaring an onClickListener all I am doing is setOnClickListener(new View.OnClickListener(){ onClick(){system.out.print("test")}} so how does android knows to access the method when a button let say is press because all I am doing is declaring an instance of a class but not telling the class to use the method. – AnotherRandomUser Nov 16 '15 at 02:02
-
It knows that your object has implemented the `onClick` method so it simply calls it once it sees fit. IOW, It specified that you need to implement the onClick method since it defined that it needs a listener with that type. – zapl Nov 16 '15 at 02:03
-
Thanks for answering. I understand it now. – AnotherRandomUser Nov 16 '15 at 02:06