我有 2 个片段,FragA 和 FragB,我想将一个字符串从 FragA 传递给 FragB。我使用了这些参考资料, http: //developer.android.com/guide/components/fragments.html#CommunicatingWithActivity & http://developer.android.com/training/basics/fragments/communicating.html
我对下一步仍然有些困惑。我需要对这段代码做什么才能将 FragA 中的字符串传递给 FragB?请张贴代码。
我的 FragA 中有:
public class FragA extends ListFragment{
OnDataPass dataPasser;
public interface OnDataPass{
public void onDataPass(String data);
}
@Override
public void onAttach(Activity a) {
super.onAttach(a);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
dataPasser = (OnDataPass) a;
} catch (ClassCastException e) {
throw new ClassCastException(a.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String libraryList;
//Get the position the user clicked.
Fragment newFragment = null;
libraryList = l.getItemAtPosition(position).toString();
dataPasser.onDataPass(libraryList);
...
}
在我的主要活动中,我添加了:
public class MainActivity extends Activity implements OnDataPass{
...
@Override
public void onDataPass(String data) {
// TODO Auto-generated method stub
}
}
片段B:
public class FragB extends ListFragment{
TestAdapter mDbHelper;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
mDbHelper = new TestAdapter(getActivity());
mDbHelper.createDatabase();
mDbHelper.open();
//Get info from FragA
//Close the database.
mDbHelper.close();
}
}