call method from fragment to Activity

前端 未结 4 2140
孤城傲影
孤城傲影 2021-01-26 06:53

hello i have activity and i call many fragment based on my application business i need to call method from fragment in activity i searched in the internet but i cannot find the

4条回答
  •  心在旅途
    2021-01-26 07:42

    Call method of Activity from fragment

     ((YourActivityName)getActivity()).addUserLineInfoFragment();
    

    Call method of fragment from Activity

    1. Create Interface

     public interface OnButtonListener
        {
            void onButtonClick();
        }
    

    2. Init in Activity

     protected OnButtonListener onActionButtonListener;
    
        public void setOnButtonListener(OnButtonListener actionButtonListener)
        {
            this.onActionButtonListener = actionButtonListener;
        }
    

    3. In Activity, click event when this action need to perform

    this.onActionButtonListener.onButtonClick();
    

    4. Implement listener(OnButtonListener) in Fragment

     @Override
        public void onButtonClick(){}
    

    5. In fragment onCreateView

    ((YourActivityName) getActivity()).setOnButtonListener(this);
    

提交回复
热议问题