简体   繁体   English

如何将数据从片段发送到片段?

[英]How to send data from fragment to fragment?

I have 1 layout. 我有1个布局。 It contains 2 fragments. 它包含2个片段。 There are 2 buttons in this layout. 此布局中有2个按钮。 When I clicked button 1, the fragment 1 is going to display. 当我单击按钮1时,片段1将显示。 I am going to click button in fragment 1 content of textview display "welcome" then i click button 2 in main layout, fragment 2 is going to display and textview of fragment 2 is going to display content of textview of fragment 1. 我将点击文本视图显示“欢迎”的片段1内容中的按钮,然后我在主布局中单击按钮2,片段2将显示,片段2的textview将显示片段1的textview的内容。

Here This is my code.Please show and give me some comment for me.How to reslove this issue The first is mainlayout.xml 这是我的代码。请给我看一些评论。如何重新解决这个问题首先是mainlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >   

<Button
    android:id="@+id/btnFragment1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="fragment1" />

<Button
    android:id="@+id/btnFragment2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Fragment2" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:id="@+id/container">
</LinearLayout>

The first is fragment1.xml 第一个是fragment1.xml

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />


The first is fragment1.java 第一个是fragment1.java

 public class Fragment1 extends Fragment{

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
}



@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = null;
    view = inflater.inflate(R.layout.fragment1, null);
           //I will get text after I press button and using bundle for storage
             and send send to fragment
    return view;
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

@Override
public void onDestroyView() {
    // TODO Auto-generated method stub
    super.onDestroyView();
}

@Override
public void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
}

@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
}

@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();
}

@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
}}

The first is fragment2.xml 第一个是fragment2.xml

 <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />  

The first is fragment2.java 第一个是fragment2.java

public class Fragment2 extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragment2, null);
        //In this I am going to using Bundle to get message from fragment1
}}

The first is MainActivity.java 第一个是MainActivity.java

 public class MainActivity extends FragmentActivity {

Button btnFragment1, btnFragment2;
FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    fragmentManager = getSupportFragmentManager();

    btnFragment1 = (Button) findViewById(R.id.btnFragment1);
    btnFragment1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            transaction.replace(R.id.container, new Fragment1(), "TAG_FRAGMENT1");
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

    btnFragment2 = (Button) findViewById(R.id.btnFragment2);
    btnFragment2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            transaction.replace(R.id.container, new Fragment2(), "TAG_FRAGMENT2");
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}}

Use a interface as a call back to the activity and then communicate the data to fragment2 使用接口作为对活动的回调,然后将数据传递给fragment2

http://developer.android.com/training/basics/fragments/communicating.html http://developer.android.com/training/basics/fragments/communicating.html

There is a Example in the above link 上面的链接中有一个例子

@Raghunandan has a good answer. @Raghunandan有一个很好的答案。 Not the only option though, you could use a BroadcastManager or LocalBroadcastManager. 不是唯一的选择,你可以使用BroadcastManager或LocalBroadcastManager。 This way you can easily respond to events across Activities, Fragments, Services, etc. 通过这种方式,您可以轻松响应活动,碎片,服务等各种事件。

how to use LocalBroadcastManager? 如何使用LocalBroadcastManager?

You can use Activity as a proxy between fragments this is how you can inform Activity about event in fragment: 您可以使用Activity作为片段之间的代理,这是您可以通过片段告知Activity有关事件的信息:

public class FragmentA extends Fragment {
    OnSomethingDoneInFragmentListener mListener;

    //this inteface must implement Activity that use the fragment
    public interface OnSomethingDoneInFragmentListener {
        public void onSomethingDone(Object someObject);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnSomethingDoneInFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnSomethingDoneInFragmentListener");
        }
    }
}

Try to use EventBus , it saves you a lot of work. 尝试使用EventBus ,它可以为您节省大量的工作。

EventBus is an Android optimized publish/subscribe event bus. EventBus是Android优化的发布/订阅事件总线。 A typical use case for Android apps is gluing Activities, Fragments, and background threads together. Android应用程序的典型用例是将活动,片段和后台线程粘合在一起。 Conventional wiring of those elements often introduces complex and error-prone dependencies and life cycle issues. 这些元件的传统布线通常会引入复杂且容易出错的依赖性和生命周期问题。 With EventBus propagating listeners through all participants (eg background service -> activity -> multiple fragments or helper classes) becomes deprecated. EventBus通过所有参与者(例如后台服务 - >活动 - >多个片段或帮助程序类)传播监听器变得不推荐使用。 EventBus decouples event senders and receivers and thus simplifies communication between app components. EventBus将事件发送者和接收者分离,从而简化了应用程序组件之间的通信。 Less code, better quality. 代码更少,质量更好。 And you don't need to implement a single interface! 而且您不需要实现单个界面!

Define your event, which is a data object: 定义您的事件,这是一个数据对象:

class MyClickEvent {
    // ...
    public MyClickEvent(String field1, int field2) {
        // ...
    }
}

In a Fragment, register itself to handle event: 在片段中,注册自己来处理事件:

class MyFragment extends Fragment {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // ...
        EventBus.getDefault().register(this, MyClickEvent.class);
    }   

    public void onEvent(MyClickEvent event) {
        // handle the event
    }
}

Post event on button click: 点击按钮后发布活动:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        EventBus.getDefault().post(new MyClickEvent("Some data", 123456));
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM