Fragment activity communication by passing Context object to onAttach()

前端 未结 1 1091
慢半拍i
慢半拍i 2020-12-12 07:14

Im trying to implement fragment to activity communication.

Went through android developer doc where an Activity object is passed to onAttach life cycle and set up th

相关标签:
1条回答
  • 2020-12-12 08:08

    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 :)

    0 讨论(0)
提交回复
热议问题