简体   繁体   中英

Pass data between fragments

I have one MainActivity and two fragments. In FragmentA I have a recycler view. If I click on "add" button there, the FragmentB is open. The thing I would like to is to write text into some EditTexts and send data back to FragmentA (and render that data in the recycler view). Could you suggest me something please? Thanks

FragmentB

public class NewContactFragment extends Fragment {

    EditText name, number, email;
    public String mName;
    public String mNumber;
    public String mEmail;
    boolean isFavourite = false;

    public NewContactFragment() {
        // Required empty public constructor
    }

    public static NewContactFragment newInstance() {
        NewContactFragment fragment = new NewContactFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);

        return fragment;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);

        //set title
        ((MainActivity) getActivity()).getSupportActionBar().setTitle(R.string.new_contact);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_new_contact, container, false);

        name = (EditText) view.findViewById(R.id.ed_name);
        number = (EditText) view.findViewById(R.id.ed_number);
        email = (EditText) view.findViewById(R.id.ed_email);

        mName = name.getText().toString();
        mNumber = number.getText().toString();
        mEmail = email.getText().toString();

        return view;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.new_contact_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_done:
                //TODO: save editTexts and return to ContactListFragment

                break;
            case R.id.action_favourite:
                getActivity().invalidateOptionsMenu();
                //Toast.makeText(getContext(), "isFavourite is: " + isFavourite, Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

FragmentA

public class ContactListFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = "newcontact";
    FloatingActionButton fabButton;
    SearchView searchView;
    RecyclerView recyclerView;
    ContactsAdapter contactsAdapter;
    List<Contact> mContact = new ArrayList<>();

    public static ContactListFragment newInstance() {
        Bundle args = new Bundle();
        ContactListFragment fragment = new ContactListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_contact_list, container, false);

        searchView = (SearchView) view.findViewById(R.id.search_view);
        fabButton = (FloatingActionButton) view.findViewById(R.id.fab_button);
        fabButton.setOnClickListener(this);

        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mContact = SugarRecord.listAll(Contact.class);
        contactsAdapter = new ContactsAdapter(getActivity(), mContact);
        recyclerView.setAdapter(contactsAdapter);

        inputFilter();

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);

        //show actionBar
        ((MainActivity) getActivity()).getSupportActionBar().show();
        //show title
        ((MainActivity) getActivity()).getSupportActionBar().setTitle(R.string.app_name);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    public void inputFilter() {
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                contactsAdapter.filterList(newText);
                return true;
            }
        });
    }

    @Override
    //Fab button listener
    public void onClick(View v) {
        ((MainActivity) getActivity()).showFragment(new NewContactFragment(), TAG);
    }

Fragments should generally only communicate with their direct parent activity. Fragments communicate through their parent activity allowing the activity to manage the inputs and outputs of data from that fragment coordinating with other fragments or activities. Think of the Activity as the controller managing all interaction with each of the fragments contained within.

A few exceptions to this are dialog fragments presented from within another fragment or nested child fragments . Both of these cases are situations where a fragment has nested child fragments and that are therefore allowed to communicate upward to their parent (which is a fragment).

The important thing to keep in mind is that fragments should not directly communicate with each other and should generally only communicate with their parent activity . Fragments should be modular, standalone and reusable components. The fragments allow their parent activity to respond to intents and callbacks in most cases.

There are three ways a fragment and an activity can communicate:

  • Bundle - Activity can construct a fragment and set arguments
  • Methods - Activity can call methods on a fragment instance
  • Listener - Fragment can fire listener events on an activity via an interface

In other words, communication should generally follow these principles:

Read more about Fragment and its communication at Creating and Using Fragments

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