我需要将5个片段之间的数据传递给一个Activity,当我到达第5个片段时,这些片段会一个接一个地发送数据,那么我需要存储所有的5个片段数据.任何想法都是伟大的.
解决方法
将数据从每个片段传递到活动,当活动获取所有数据然后处理它.
您可以使用接口传递数据.
您可以使用接口传递数据.
分段:
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); } }