Sharing Data between two Fragments of of one Activ

2019-09-12 02:13发布

问题:

Ive got two Fragments. One for data Input and one to display them in a ListView. But I dont know how to send data from Fragment 1 to Fragment 2...

I know that I can get Data from my MainActivity to Fragment 1 with the following Code:

String listElement = getActivity().getIntent().getStringExtra("com.sample.MESSAGE");

But how do I send the string from Fragment 2 to my Activity?

UPDATE: I'm not quite sure if I'm doing this right... I used Harlo Holmes Tutorial (posted below) and not Ive got this Fragment Code

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;


    public class AddDataFragment extends Fragment {

        public interface OnDataPass {
            public void onDataPass(String data);
        }

        Button buttonadd;
        Button buttondelete;

        private EditText inputProduct;

        private TextView listElement;

        OnDataPass dataPasser;

        @Override
        public void onAttach(Context context){
            super.onAttach(context);

            Activity a;

            if (context instanceof Activity){
                a=(Activity) context;
            }
            dataPasser = (OnDataPass) context;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,                                            Bundle savedInstanceState) {

            View view = inflater.inflate(R.layout.fragment_add_data, container, false);
            inputProduct = (EditText) view.findViewById(R.id.editText_product);
            buttonadd = (Button) view.findViewById(R.id.button_add_addData);
            buttondelete = (Button) view.findViewById(R.id.button_delete_addData);

            listElement = (TextView) view.findViewById(R.id.productTest);

            buttonadd.setEnabled(true);
            buttondelete.setEnabled(true);

            buttonadd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listElement.setText(getString(R.string.ListElementPlaceholder,                           inputProduct.getText()));
                }
                public void passData(String listElement){
                    dataPasser.onDataPass(listElement);
                }
            });

            return view;
        }


}

There where some issues with the onAttach method... Is this the right way?

回答1:

An interface is the most common way when it comes to a Fragment communicating with its hosting Activity. The link by Nandakishore Shetty in the comments references the method recommended in the Android Docs, which is the method I use and is very stable (edited example below).

public class MyFragment extends Fragment {

    MyFragmentListener mCallback;

    // Container Activity must implement this interface
    public interface MyFragmentListener {
        public void methodToImplemet(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (MyFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement MyFragmentListener");
        }
    }

    ...
}

Somewhere inside your Fragment, you would then call mCallback.methodToImplement(position); (i.e. inside an onClick())

Then, inside your Activity:

public class MainActivity extends Activity implements MyFragmentListener {
    //...
    @Override
    public void methodToImeplement(int position) {
        Log.e(getClass().getSimpleName(), "position: " + position);
    }

Here's a link to a sample app showing Fragment/Activity communication I put together for a similar SO question.

Other alternatives include using an EventBus of some kind, such as LocalBroadcastManager or a third party library.



回答2:

Data can be pass from fragment to activity using interfaces .

Detail description :

Passing data between a fragment and its container activity

Hope it will help you.