片段沟通。我有一点困惑

时间:2012-09-06 00:48:27

标签: android fragment

我有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

}
}

FragB:

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();

}
}

1 个答案:

答案 0 :(得分:0)

我认为您应该在OnDataPass中实施FragB界面,然后在Activity.onDataPass中找到FragB个实例并致电FragB.onDataPass。这是我认为最清晰的方式。