天天看点

Fragment 之间的传值

以我目前的水平,所能自己创造的类和类之间的传值基本上都是通过接口进行,例如使用异步任务AsyncTask 进行数据的加载 之后将数据通过接口回调的形势回传给activity 或者Fragment 来进行UI的更新

1. 首先建立接口,这个步骤可以在Fragment 内部实现也可以自己单独在其他实现,然后在其中一个Fragment 内部定义接口的对象

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
    public void onArticleSelected(int position);
}

@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");
    }
}
           
  1. 让Activity实现这个接口,并在Fragment 的OnAttach 方法把activity对象强转为接口对象

    public static class MainActivity extends Activity

    implements HeadlinesFragment.OnHeadlineSelectedListener{

    public void onArticleSelected(int position) {

    // The user selected the headline of an article from the HeadlinesFragment

    // Do something here to display that article

    }

3.传递消息

public static class MainActivity extends Activity

implements HeadlinesFragment.OnHeadlineSelectedListener{

public void onArticleSelected(int position) {
    // The user selected the headline of an article from the HeadlinesFragment
    // Do something here to display that article

    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 {
        // Otherwise, 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();
    }
}
           

}