简体   繁体   中英

Passing Object from Fragment to Activity

Question: How do I pass objects from fragment to activity (on request from activity).

Background: I am using Android Studio and have set up a new tabbed activity from the New Android Activity wizard. I have then defined 5 fragments that each contain different sets of inputs (edit texts and so on). Each input form then populates a custom object so that it can be passed to the tab host activity. I will then save the objects in a database once an 'Add button' is pressed on the task bar (this is where the objects should be taken in from fragments). However I cannot find a way to pass the objects from the fragments to the activity. Previously I have passed objects between activities by using and calling a 'getObject()' method, this doesn't seem to work for the fragments.

My fragments do not currently have an 'onAttach' method, I'm not too sure what this does.

Thanks in advance for any help.

You could have an interface:

public interface MyInterface {
    void doSomethingWithData(Object data);
}

then in the activity class:

public class MyActivity extends Activity implements MyInterface {
    ...
    public void doSomethingWithData(Object data) {
        // save your data in database
    }
    ...
}

and in fragments:

public class MyFragment extends Fragment {
    ...
    private MyInterface listener;
    ...
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MyInterface) {
            listener = (MyInterface) context;
        }
    }

    @Override
    public void onDetach() {
        listener = null;
        super.onDetach();
    }
    ...
    // Somewhere in code .. where you want to send data to the activity
    listener.doSomethingWithData(data);
    ...
}

The Activity has instances of the fragments, so when you are pressing the Add button, you can collect your data from the fragments.

for example, from the TabActivity:

int cards = fragment1.getCards();
String name = fragment2.getUserName();

etc.

Just create does public methods in the Fragments.

您可以创建一个DataManger Singelton类,并在该对象的decalare getter setter中创建,并在整个项目中使用它。

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