Here is a small example that will describe you the communication between Activity
and Fragment
. Suppose you have a Interface ICommunication
. This is given below:
public interface ICommunication {
public void testMethod();
}
Now you have a Activity
name MainActivity
that implements ICommunication
then it must have implements the method testMethod()
. This method will like this:
@Override
public void testMethod() {
Toast toast = Toast.makeText(getActivity(), "It's called from Fragment", Toast.LENGTH_SHORT).show();
}
Now, suppose this MainActivity
belongs a Fragment
name TestFragment
. If you want to access testMethod()
of MainActivity from TestFragment
then you can simply call using this way :
((ICommunication)getActivity()).testMethod();
Here , TestFragment
must be hold on MainActivity
.
My related answer with source is here
Thats it :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…