Calling a method in one fragment from another

前端 未结 5 1512
渐次进展
渐次进展 2020-12-18 00:30

I\'ve been trying for a while already (as well, searching in here) for something to help me to refresh listView in my MainFragment, when a button is pressed in other fragmen

5条回答
  •  半阙折子戏
    2020-12-18 01:09

    you should use interface for this. define an interface in OtherFragment class and implement that in your MainActivity and define a public method in your MainFragment for refreshing your ListView and call that method from your MainActivity. here is an example :

    public Class OtherFragment extends Fragment implements OnClickListener {
    
    private Communicator communicator;
    
       ...
    
    public void setCommunicator(Communicator communicator) {
        this.communicator = communicator;
    }
    
    @Override
    public void onClick(View v) {
       communicator.clicked();
    }
    
       public interface Communicator {
          public void clicked();
       }
    }
    

    and in your MainActivity :

    public class MainActivity extends Activity implements OtherFragment.Communicator {
    
       MainFragment mainFragment;
    
       @Override
       protected void onCreate(Bundle b) {
          ...
          OtherFragment otherFragment = new OtherFragment();
          otherFragment.setCommunicator(this);
          ...
       }
    
       ...
    
       @Override 
       public void clicked() {
         mainFragment.updateList();
       }
    }
    

    and in your MainFragment :

    public class MainFragment extends Fragment {
    
        ...
    
        public void updateList() {
            // update list
        }
    }
    

提交回复
热议问题