Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

android - How to communicate between fragments?

I am developing an Android application. I have a requirement like there is a button in fragment 1, when a user clicks that button result should be displayed in fragment 2. While loading the activity both fragments is attached. Here is my try:

In main activity:

    public void dsp(String str) {
    secondfragment f2=new secondfragment();
    Bundle bundle = new Bundle();
    bundle.putString("edttext", "From Activity");

    f2.setArguments(bundle);
    }

In first fragment:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.fragone, container,false);
    Button btn = (Button) v.findViewById(R.id.button1); 
    btn.setOnClickListener(new OnClickListener() {           
          @Override
          public void onClick(View v) 
          {
              m.dsp("clicked");
          }    
        });
    return v;
}

In second fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.fragtwo, container,false);
    tv= (TextView) v.findViewById(R.id.textView1);

    tv.setText(this.getArguments().getString("name"));

    return v;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here you have what the Android Documentation says about Communicating Between Fragments. Here you'll have all the necessary steps to make two or more fragments communicate securely :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...