Basic communication between two fragments

前端 未结 10 2338
我寻月下人不归
我寻月下人不归 2020-11-22 05:00

I have one activity - MainActivity. Within this activity I have two fragments, both of which I created declaratively within the xml.

I am trying to pas

10条回答
  •  离开以前
    2020-11-22 05:37

    Update

    Ignore this answer. Not that it doesn't work. But there are better methods available. Moreover, Android emphatically discourage direct communication between fragments. See official doc. Thanks user @Wahib Ul Haq for the tip.

    Original Answer

    Well, you can create a private variable and setter in Fragment B, and set the value from Fragment A itself,

    FragmentB.java

    private String inputString;
    ....
    ....
    
    public void setInputString(String string){
       inputString = string;
    }
    

    FragmentA.java

    //go to fragment B
    
    FragmentB frag  = new FragmentB();
    frag.setInputString(YOUR_STRING);
    //create your fragment transaction object, set animation etc
    fragTrans.replace(ITS_ARGUMENTS)
    

    Or you can use Activity as you suggested in question..

提交回复
热议问题