Reputation: 349
i have been looking for and i found this ...
interface CallBack {
void methodToCallBack();
}
class CallBackImpl implements CallBack {
public void methodToCallBack() {
System.out.println("I've been called back");
}
}
class Caller {
public void register(CallBack callback) {
callback.methodToCallBack();
}
public static void main(String[] args) {
Caller caller = new Caller();
CallBack callBack = new CallBackImpl();
caller.register(callBack);
}
}
what's difference with this other.
interface CallBack {
void methodToCallBack();
}
class CallBackImpl implements CallBack {
public void methodToCallBack() {
System.out.println("I've been called back");
}
}
class Caller {
public static void main(String[] args) {
CallBack callBack = new CallBackImpl();
callBack.methodToCallBack();
}
}
my situation: I have a onclicklistener (only a child not complete row) within of adapter y when this listener execute ,i wanna execute a method on activity because in activity i have access UI..
Upvotes: 1
Views: 971
Reputation: 4636
Purpose of callbacks is for asynchronous communication. You tell somebody that let me know when something happened through callback (phone number). Apart from this, the advantage I felt with callbacks is that:
- you can avoid dependency between the classes.
- helps avoiding memory leaks.
Take an example of communication from fragment to activity. Though you can call getActivity().aMethodInActivity() it is not preferable because it violates one of the purpose of fragments that is ''reusability'. And we may tend to pass activity instance to fragment which may lead to activity leaks.
Same is the case with fragments and adapters. Communication from adapter to fragment should happen using callbacks. Otherwise if fragment is passed as parameter to adapter, adapter is holding reference to fragment and fragment is holding the reference of adapter. This may lead to leaks.
I tried to explain the advantage of callbacks from android perspective with couple of examples I know. You can explore further.
Upvotes: 1
Reputation: 53
This should do exactly what you want : Communicating with Other Fragments
Upvotes: 0
Reputation: 435
With the first method, you register to the Callback, so methodToCallBack can be called automatically.
u say you have an OnClickListener, i guess it is in another class. You can create it as inner class, so you will have acces to your UI.
Or you give your OnClickListener everything he needs in the Constructor
Upvotes: 0