Passing data between a fragment and its container

2018-12-31 03:24发布

How can I pass data between a fragment and its container activity? Is there something similar to passing data between activities through intents?

I read this, but it didn't help much:
http://developer.android.com/guide/topics/fundamentals/fragments.html#CommunicatingWithActivity

12条回答
浮光初槿花落
2楼-- · 2018-12-31 03:51

Passing data between a fragment and its container activity

Activity:

        Bundle bundle = new Bundle();
        bundle.putString("message", "Alo Elena!");
        FragmentClass fragInfo = new FragmentClass();
        fragInfo.setArguments(bundle);
        transaction.replace(R.id.fragment_single, fragInfo);
        transaction.commit();

Fragment:

Reading the value in the fragment

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        String myValue = this.getArguments().getString("message");
        ...
        ...
        ...
        }
查看更多
何处买醉
3楼-- · 2018-12-31 03:54

Easiest Approach but not Recommended

You can access activity data from fragment:

Activity:

public class MyActivity extends Activity {

    private String myString = "hello";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        ...
    }

    public String getMyData() {
        return myString;
    }
}

Fragment:

public class MyFragment extends Fragment {

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

        MyActivity activity = (MyActivity) getActivity();
        String myDataFromActivity = activity.getMyData();
        return view;
    }
}
查看更多
倾城一夜雪
4楼-- · 2018-12-31 03:58
public class Fragmentdemo extends Fragment {

  public interface onDemoEventListener {
    public void demoEvent(String s);
  }

  onDemoEventListener demoEventListener;

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

  final String LOG_TAG = "TAG";

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragmentdemo, null);

    Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        demoEventListener.someEvent("Test text to Fragment1");
      }
    });
    enter code here
    return v;
  }
}
查看更多
还给你的自由
5楼-- · 2018-12-31 04:01
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Bundle b = getActivity().getIntent().getExtras();
            wid = b.getString("wid");
            rid = b.getString("rid");
            View view = inflater.inflate(R.layout.categoryfragment, container, false);
    return view;
 }
查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 04:01

Simply you can use EventBus it is easy and work great

EventBus in 3 steps

  1. Define events:

    public static class MessageEvent { /* Additional fields if needed */ }

  2. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */};

Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

 @Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }
  1. Post events:

    EventBus.getDefault().post(new MessageEvent());

查看更多
心情的温度
7楼-- · 2018-12-31 04:03

Try using interfaces.

Any fragment that should pass data back to its containing activity should declare an interface to handle and pass the data. Then make sure your containing activity implements those interfaces. For example:

In your fragment, declare the interface...

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

Then, connect the containing class' implementation of the interface to the fragment in the onAttach method, like so:

OnDataPass dataPasser;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    dataPasser = (OnDataPass) context;
}

Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:

public void passData(String data) {
    dataPasser.onDataPass(data);
}

Finally, in your containing activity which implements OnDataPass...

@Override
public void onDataPass(String data) {
    Log.d("LOG","hello " + data);
}
查看更多
登录 后发表回答