简体   繁体   中英

How to send data from fragment to fragment?

I have 1 layout. It contains 2 fragments. There are 2 buttons in this layout. When I clicked button 1, the fragment 1 is going to display. I am going to click button in fragment 1 content of textview display "welcome" then i click button 2 in main layout, fragment 2 is going to display and textview of fragment 2 is going to display content of textview of fragment 1.

Here This is my code.Please show and give me some comment for me.How to reslove this issue The first is mainlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >   

<Button
    android:id="@+id/btnFragment1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="fragment1" />

<Button
    android:id="@+id/btnFragment2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Fragment2" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:id="@+id/container">
</LinearLayout>

The first is fragment1.xml

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />


The first is fragment1.java

 public class Fragment1 extends Fragment{

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
}



@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = null;
    view = inflater.inflate(R.layout.fragment1, null);
           //I will get text after I press button and using bundle for storage
             and send send to fragment
    return view;
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

@Override
public void onDestroyView() {
    // TODO Auto-generated method stub
    super.onDestroyView();
}

@Override
public void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
}

@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
}

@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
}

@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
}}

The first is fragment2.xml

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />  

The first is fragment2.java

public class Fragment2 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragment2, null);
        //In this I am going to using Bundle to get message from fragment1
}}

The first is MainActivity.java

 public class MainActivity extends FragmentActivity {

Button btnFragment1, btnFragment2;
FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    fragmentManager = getSupportFragmentManager();

    btnFragment1 = (Button) findViewById(R.id.btnFragment1);
    btnFragment1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            transaction.replace(R.id.container, new Fragment1(), "TAG_FRAGMENT1");
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

    btnFragment2 = (Button) findViewById(R.id.btnFragment2);
    btnFragment2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            transaction.replace(R.id.container, new Fragment2(), "TAG_FRAGMENT2");
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}}

Use a interface as a call back to the activity and then communicate the data to fragment2

http://developer.android.com/training/basics/fragments/communicating.html

There is a Example in the above link

@Raghunandan has a good answer. Not the only option though, you could use a BroadcastManager or LocalBroadcastManager. This way you can easily respond to events across Activities, Fragments, Services, etc.

how to use LocalBroadcastManager?

You can use Activity as a proxy between fragments this is how you can inform Activity about event in fragment:

public class FragmentA extends Fragment {
    OnSomethingDoneInFragmentListener mListener;

    //this inteface must implement Activity that use the fragment
    public interface OnSomethingDoneInFragmentListener {
        public void onSomethingDone(Object someObject);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnSomethingDoneInFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnSomethingDoneInFragmentListener");
        }
    }
}

Try to use EventBus , it saves you a lot of work.

EventBus is an Android optimized publish/subscribe event bus. A typical use case for Android apps is gluing Activities, Fragments, and background threads together. Conventional wiring of those elements often introduces complex and error-prone dependencies and life cycle issues. With EventBus propagating listeners through all participants (eg background service -> activity -> multiple fragments or helper classes) becomes deprecated. EventBus decouples event senders and receivers and thus simplifies communication between app components. Less code, better quality. And you don't need to implement a single interface!

Define your event, which is a data object:

class MyClickEvent {
    // ...
    public MyClickEvent(String field1, int field2) {
        // ...
    }
}

In a Fragment, register itself to handle event:

class MyFragment extends Fragment {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // ...
        EventBus.getDefault().register(this, MyClickEvent.class);
    }   

    public void onEvent(MyClickEvent event) {
        // handle the event
    }
}

Post event on button click:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        EventBus.getDefault().post(new MyClickEvent("Some data", 123456));
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM