2

在我的 MainActivity 扩展了 FragmentActivity,我有一个 FragmentA,当我按下 FragmentA 中的一个按钮时,我调用 FragmentB。

FragmentB f = FragmentB.newInstance(1);
        getSupportFragmentManager().beginTransaction().replace(R.id.llMain, f).addToBackStack(null).commit(); 

在 FragmentB 中,我创建了一个 Object People p1(with Name and age) 。当我按下 FragmentB 中的按钮 B 时,我打电话

getFragmentManager().popBackStack();

它将返回 FragmentA,

所以,我想将数据对象 People p1 从 FragmentB 传递到 FragmentA。我需要做什么?我尝试搜索但找不到解决方案。

4

2 回答 2

0

在你的 Fragment 中创建 CallBack 并在 FragmentActivity 中处理, google example 有这个实现

声明 OnHeadlineSelectedListener 回调

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;

// The container Activity must implement this interface so the frag can deliver messages
public interface OnHeadlineSelectedListener {
    /** Called by HeadlinesFragment when a list item is selected */
    public void onArticleSelected(int position);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    // Create an array adapter for the list view, using the Ipsum headlines array
    setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception.
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Notify the parent activity of selected item
    mCallback.onArticleSelected(position);

    // Set the item as checked to be highlighted when in two-pane layout
    getListView().setItemChecked(position, true);
}

在 FragmentActivity 中实现回调方法,如果 ArticleFragment 可用,则将 HeadLinesFragment 中的数据(通过 .setArguments())发送到 ArticleFragment

public class MainActivity extends FragmentActivity 
    implements HeadlinesFragment.OnHeadlineSelectedListener {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment firstFragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    }
}

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment

    // Capture the article fragment from the activity layout
    ArticleFragment articleFrag = (ArticleFragment)
            getSupportFragmentManager().findFragmentById(R.id.article_fragment);

    if (articleFrag != null) {
        // If article frag is available, we're in two-pane layout...

        // Call a method in the ArticleFragment to update its content
        articleFrag.updateArticleView(position);

    } else {
        // If the frag is not available, we're in the one-pane layout and must swap frags...

        // Create fragment and give it an argument for the selected article
        ArticleFragment newFragment = new ArticleFragment();
        Bundle args = new Bundle();
        args.putInt(ArticleFragment.ARG_POSITION, position);
        newFragment.setArguments(args);
        FragmentTransaction transaction =             getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }
}
于 2013-08-21T10:15:28.643 回答
-1

您应该在 Activity 中使用接口来进行片段之间的通信。检查这个android 培训课程

所有 Fragment 到 Fragment 的通信都是通过关联的 Activity 完成的。两个 Fragment 永远不应该直接通信。

您可以将参数传递给带有Bundle. 将您的代码更改为:

FragmentB f = FragmentB.newInstance(1);

Bundle args = new Bundle();
args.putString("NAME", name);
args.putInt("AGE", age);
f.setArguments(args);

getSupportFragmentManager().beginTransaction().replace(R.id.llMain, f).addToBackStack(null).commit();

然后在 FragmentA 的 onCreateView 中检索参数,例如:

int age = getArguments().getInt("AGE");
//or with a second parameter as the default value
int age = getArguments().getInt("AGE", 0);

如果要将整个 People 对象传递给 Bundle,则需要使类可序列化。我认为传递变量然后重新创建对象更容易。

于 2013-08-21T10:09:45.157 回答