将片段之间的数据传递给活动

时间:2013-01-21 13:40:34

标签: android

我需要在5 fragmentsActivity之间传递数据,当{到达fragments然后我fragment时,fragments会一个接一个地发送数据需要存储所有5个{{1}}数据,我们如何才能这样做。任何想法都很棒。enter image description here

6 个答案:

答案 0 :(得分:39)

当活动获取所有数据然后处理它时,将每个片段的数据传递给活动。 您可以使用接口传递数据。

片段:

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

答案 1 :(得分:9)

以下链接说明了片段之间的通信设计。

Communicating with Other Fragments

要允许Fragment与其Activity进行通信,您可以在Fragment类中定义接口并在Activity中实现它。 Fragment在其onAttach()生命周期方法中捕获接口实现,然后可以调用Interface方法以与Activity通信。

以下是片段到活动通信的示例:

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");
    }
}

...
}

现在,片段可以通过使用OnHeadlineSelectedListener接口的mCallback实例调用onArticleSelected()方法(或接口中的其他方法)来向活动传递消息。

例如,当用户单击列表项时,将调用片段中的以下方法。该片段使用回调接口将事件传递给父活动。

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Send the event to the host activity
    mCallback.onArticleSelected(position);
}

实施界面

为了从片段接收​​事件回调,托管它的活动必须实现片段类中定义的接口。

例如,以下活动实现了上例中的接口。

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
}
}

向片段发送消息

主机活动可以通过使用findFragmentById()捕获Fragment实例,然后直接调用片段的公共方法,将消息传递给片段。

例如,假设上面显示的活动可能包含另一个片段,该片段用于显示上述回调方法中返回的数据指定的项目。在这种情况下,活动可以将回调方法中收到的信息传递给将显示该项目的另一个片段:

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

答案 2 :(得分:5)

您必须将信息返回到您的片段活动。并且您的活动将信息发送到其片段:

// In fragment A
((ParentActivity)getActivity()).dispatchInformations("test");

// In ParentActivity
public void dispatchInformations(String mesg){
    fragmentB.sendMessage(mesg);
}

这是一个基本的例子

答案 3 :(得分:1)

我尝试了以上所有内容并没有对我有用。这就是我使它工作的方式。我使用接口作为将数据从片段发送到活动的手段。

FragmentToActivity.java

public interface FragmentToActivity {
void communicate(String comm);

}

FragmentOne

public class FragmentOne extends Fragment {

private FragmentToActivity mCallback;


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mCallback = (FragmentToActivity) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + " must implement FragmentToActivity");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_login, container, 
false);
sendData("Andrews");

return v;
}
@Override
public void onDetach() {
    mCallback = null;
    super.onDetach();
}

public void onRefresh() {
    Toast.makeText(getActivity(), "Fragment : Refresh called.",
            Toast.LENGTH_SHORT).show();
  }
private void sendData(String comm)
    {
    mCallback.communicate(comm);

    }

 }


}

活动一

public class Account extends AppCompatActivity implements 
  FragmentToActivity{

  @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 }

@Override
public void communicate(String s) {


    Log.d("received", s);
      }


}

答案 4 :(得分:1)

您可以使用上述答案中说明的Communicator模式。 此外,您可以使用RxJava2。以获得更好的解耦和效率。

1-创建总线:

srtli=[]
for ele in li:
    tmp=ele[1:]
    tmp.sort()
    for ele_tmp in tmp:
        ele_tmp[1].sort()
    srtli.append([ele[0]]+tmp)
srtli.sort()

2-发件人活动或片段

public final class RxBus {

    private static final BehaviorSubject<Object> behaviorSubject
        = BehaviorSubject.create();


    public static BehaviorSubject<Object> getSubject() {
        return behaviorSubject;
    }

}

3 - 接收者活动或片段

//the data to be passed
MyData  data =getMyData();
RxBus.getSubject().onNext(data) ;

4-unSubscribe以避免内存泄漏:

private Subscription subscription;

public onCreate(Bundle savedInstanceState){
    subscription = RxBus.getSubject()
                    .subscribe(new Subscriber<Object>() {

            @Override
            public void onNext(Object o) {
                if (o instanceof MyData) {
                    Log.d("tag", (MyData)o.getData();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
}

答案 5 :(得分:-2)

有一种非常简单的方法可以将数据从Fragment传递到另一个不是其容器的Activity。

1)在片段中:当您启动活动时,例如onButtonClick,将您想要传递的数据作为额外内容传递给您,如下:

     Intent intent = new Intent(getActivity(), MapsActivity.class);
     intent.putExtra("data", dataString);
     startActivity(intent);

2)在接收活动中:在你的onCreate方法中,创建一个Bundle来检索传递的信息,如下:

Bundle extras = getIntent().getExtras();
    if (extras != null) {
        receivingString = extras.getString("data");
    } else {
        // handle case
    }

希望它有所帮助:)