传递数据片段间到活动片段、数据

由网友(北幕南辞°)分享简介:我需要从5 片段之间的数据传递给一个活动,这些片段陆续发送数据之一,当我到了第5'片段然后我需要存储的所有5 片段数据我们如何能做到这一点。任何想法是伟大的。 I need to pass data between from 5 fragments to one Activity, those fragments...

我需要从5 片段之间的数据传递给一个活动,这些片段陆续发送数据之一,当我到了第5'片段然后我需要存储的所有5 片段数据我们如何能做到这一点。任何想法是伟大的。

I need to pass data between from 5 fragments to one Activity, those fragments send data one after another when i reach 5'th fragment then i need to store all 5 fragments data how can we do this. any idea is Great.

推荐答案

从每个片段活动,当活动得到的所有数据,然后进行处理传递数据。 您可以使用接口传递数据。

Pass data from each fragment to activity, when activity gets all data then process it. You can pass data using interfaces.

片段:

    public class Fragment2 extends Fragment {

  public interface onSomeEventListener {
    public void someEvent(String s);
  }

  onSomeEventListener someEventListener;

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

  final String LOG_TAG = "myLogs";

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

    Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        someEventListener.someEvent("Test text to Fragment1");
      }
    });

    return v;
  }
}

活动:

    public class MainActivity extends Activity implements onSomeEventListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Fragment frag2 = new Fragment2();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment2, frag2);
        ft.commit();
    }

  @Override
  public void someEvent(String s) {
      Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
      ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
  }
}
阅读全文

相关推荐

最新文章