简体   繁体   English

如何在片段之间传递数据

[英]How to pass data between fragments

Im trying to pass data between two fragmens in my program.我试图在我的程序中的两个片段之间传递数据。 Its just a simple string that is stored in the List.它只是一个存储在列表中的简单字符串。 The List is made public in fragments A, and when the user clicks on a list item, I need it to show up in fragment B. The content provider only seems to support ID's, so that will not work.列表在片段 A 中公开,当用户单击列表项时,我需要它显示在片段 B 中。内容提供者似乎只支持 ID,所以这行不通。 Any suggestions?有什么建议?

I think communication between fragments should be done via activity. 我认为片段之间的交流应该通过活动来完成。 And communication between fragment and activity can be done this way: https://developer.android.com/training/basics/fragments/communicating.html https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity 片段和活动之间的通信可以通过以下方式完成: https : //developer.android.com/training/basics/fragments/communicating.html https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

Why don't you use a Bundle.为什么不使用捆绑包。 From your first fragment, here's how to set it up:从您的第一个片段开始,以下是设置方法:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Then in your second Fragment, retrieve the data using:然后在您的第二个 Fragment 中,使用以下方法检索数据:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);

Bundle has put methods for lots of data types. Bundle 为许多数据类型提供了 put 方法。 Please see http://developer.android.com/reference/android/os/Bundle.html请参阅http://developer.android.com/reference/android/os/Bundle.html

If you use Roboguice you can use the EventManager in Roboguice to pass data around without using the Activity as an interface.如果您使用 Roboguice,您可以使用 Roboguice 中的 EventManager 来传递数据,而无需使用 Activity 作为接口。 This is quite clean IMO.这是非常干净的 IMO。

If you're not using Roboguice you can use Otto too as a event bus: http://square.github.com/otto/如果您不使用 Roboguice,您也可以使用 Otto 作为事件总线: http ://square.github.com/otto/

Update 20150909: You can also use Green Robot Event Bus or even RxJava now too.更新 20150909:您现在也可以使用 Green Robot Event Bus 甚至 RxJava。 Depends on your use case.取决于您的用例。

From the Fragment documentation :Fragment 文档

Often you will want one Fragment to communicate with another, for example to change the content based on a user event.通常,您希望一个 Fragment 与另一个 Fragment 进行通信,例如根据用户事件更改内容。 All Fragment-to-Fragment communication is done through the associated Activity.所有 Fragment 到 Fragment 的通信都是通过关联的 Activity 完成的。 Two Fragments should never communicate directly.两个 Fragment 永远不应该直接通信。

So I suggest you have look on the basic fragment training docs in the documentation.所以我建议您查看文档中的基本片段培训文档。 They're pretty comprehensive with an example and a walk-through guide.它们非常全面,带有示例和演练指南。

So lets say you have Activity AB that controls Frag A and Fragment B. Inside Fragment A you need an interface that Activity AB can implement.因此,假设您有控制 Frag A 和 Fragment B 的 Activity AB。在 Fragment A 内部,您需要一个 Activity AB 可以实现的接口。 In the sample android code, they have:在示例 android 代码中,它们具有:

private Callbacks mCallbacks = sDummyCallbacks;

/*A callback interface that all activities containing this fragment must implement. /* 包含此片段的所有活动都必须实现的回调接口。 This mechanism allows activities to be notified of item selections.此机制允许将项目选择通知给活动。 */ */

public interface Callbacks {
/*Callback for when an item has been selected. */    
      public void onItemSelected(String id);
}

/*A dummy implementation of the {@link Callbacks} interface that does nothing. Used only when this fragment is not attached to an activity. */    
private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(String id) {
    }
};

The Callback interface is put inside one of your Fragments (let's say Fragment A). Callback 接口放在你的一个片段中(假设片段 A)。 I think the purpose of this Callbacks interface is like a nested class inside Frag A which any Activity can implement.我认为这个回调接口的目的就像是任何 Activity 都可以实现的 Frag A 中的嵌套类。 So if Fragment A was a TV, the CallBacks is the TV Remote (interface) that allows Fragment A to be used by Activity AB.因此,如果片段 A 是电视,则回调是允许 Activity AB 使用片段 A 的电视遥控器(接口)。 I may be wrong about the detail because I'm a noob but I did get my program to work perfectly on all screen sizes and this is what I used.我可能对细节有误,因为我是菜鸟,但我确实让我的程序在所有屏幕尺寸上都能完美运行,这就是我使用的。

So inside Fragment A, we have: (I took this from Android's Sample programs)所以在片段 A 中,我们有:(我从 Android 的示例程序中获取了这个)

@Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
//mCallbacks.onItemSelected( PUT YOUR SHIT HERE. int, String, etc.);
//mCallbacks.onItemSelected (Object);
}

And inside Activity AB we override the onItemSelected method:在 Activity AB 中,我们覆盖了 onItemSelected 方法:

public class AB extends FragmentActivity implements ItemListFragment.Callbacks {
//...
@Override
//public void onItemSelected (CATCH YOUR SHIT HERE) {
//public void onItemSelected (Object obj) {
    public void onItemSelected(String id) {
    //Pass Data to Fragment B. For example:
    Bundle arguments = new Bundle();
    arguments.putString(“FragmentB_package”, id);
    FragmentB fragment = new FragmentB();
    fragment.setArguments(arguments);
    getSupportFragmentManager().beginTransaction().replace(R.id.item_detail_container, fragment).commit();
    }

So inside Activity AB, you basically throwing everything into a Bundle and passing it to B. If u are not sure how to use a Bundle, look the class up.因此,在 Activity AB 中,您基本上将所有内容都放入 Bundle 并将其传递给 B。如果您不确定如何使用 Bundle,请查看该类。

I am basically going by the sample code that Android provided.我基本上按照 Android 提供的示例代码进行操作。 The one with the DummyContent stuff.带有 DummyContent 东西的那个。 When you make a new Android Application Package, it's the one titled MasterDetailFlow.当你创建一个新的 Android 应用程序包时,它是一个名为 MasterDetailFlow 的包。

1- The first way is define an interface 1- 第一种方式是定义一个接口

public interface OnMessage{
    void sendMessage(int fragmentId, String message);
}

public interface OnReceive{
    void onReceive(String message);
}

2- In you activity implement OnMessage interface 2- 在您的活动中实现 OnMessage 接口

public class MyActivity implements OnMessage {
   ...
   @Override
   public void sendMessage(int fragmentId, String message){
       Fragment fragment = getSupportFragmentManager().findFragmentById(fragmentId);
       ((OnReceive) fragment).sendMessage();
   }
}

3- In your fragment implement OnReceive interface 3- 在你的片段中实现 OnReceive 接口

public class MyFragment implements OnReceive{
    ...
    @Override
    public void onReceive(String message){
        myTextView.setText("Received message:" + message);
    }
}

This is the boilerplate version of handling message passing between fragments.这是处理片段之间消息传递的样板版本。

Another way of handing data passage between fragments are by using an event bus.在片段之间处理数据通道的另一种方法是使用事件总线。

1- Register/unregister to an event bus 1-注册/取消注册到事件总线

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().register(this);
}

@Override
public void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}

2- Define an event class 2- 定义一个事件类

public class Message{
    public final String message;

    public Message(String message){
        this.message = message;
    }
}

3- Post this event in anywhere in your application 3- 在您的应用程序中的任何位置发布此事件

EventBus.getDefault().post(new Message("hello world"));

4- Subscribe to that event to receive it in your Fragment 4-订阅该事件以在您的片段中接收它

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessage(Message event){
    mytextview.setText(event.message);
}

For more details, use cases, and an example project about the event bus pattern.有关事件总线模式的更多详细信息、用例和示例项目

IN my case i had to send the data backwards from FragmentB->FragmentA hence Intents was not an option as the fragment would already be initialised All though all of the above answers sounds good it takes a lot of boiler plate code to implement , so i went with a much simpler approach of using LocalBroadcastManager , it exactly does the above said but without alll the nasty boilerplate code.在我的情况下,我不得不从 FragmentB->FragmentA 向后发送数据,因此 Intents 不是一个选项,因为该片段已经被初始化尽管上述所有答案听起来都不错,但它需要大量的样板代码来实现,所以我使用了一种更简单的方法LocalBroadcastManager ,它完全符合上述要求,但没有所有讨厌的样板代码。 An example is shared below.下面分享一个例子。

In Sending Fragment(Fragment B)正在发送片段(片段B)

public class FragmentB {

    private void sendMessage() {
      Intent intent = new Intent("custom-event-name");
      intent.putExtra("message", "your message");
      LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
 }

And in the Message to be Received Fragment(FRAGMENT A)并在要接收的消息片段(FRAGMENT A)中

  public class FragmentA {
    @Override
    public void onCreate(Bundle savedInstanceState) {

      ...

      // Register receiver
      LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
          new IntentFilter("custom-event-name"));
    }

//    This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
    private BroadcastReceiver receiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("message");
      }
    };
}

Hope it helps someone希望它可以帮助某人

That depends on how the fragment is structured.这取决于片段的结构。 If you can have some of the methods on the Fragment Class B static and also the target TextView object static, you can call the method directly on Fragment Class A. This is better than a listener as the method is performed instantaneously, and we don't need to have an additional task that performs listening throughout the activity.如果您可以在 Fragment Class B 静态和目标 TextView 对象 static 上拥有一些方法,则可以直接在 Fragment Class A 上调用该方法。这比侦听器要好,因为该方法是即时执行的,我们不不需要在整个活动中执行聆听的额外任务。 See example below:请参阅下面的示例:

Fragment_class_B.setmyText(String yourstring);

On Fragment B you can have the method defined as:在片段 B 上,您可以将方法定义为:

public static void setmyText(final String string) {
myTextView.setText(string);
}

Just don't forget to have myTextView set as static on Fragment B, and properly import the Fragment B class on Fragment A.只是不要忘记在 Fragment B 上将 myTextView 设置为静态,并在 Fragment A 上正确导入 Fragment B 类。

Just did the procedure on my project recently and it worked.最近刚刚在我的项目上做了这个程序,它奏效了。 Hope that helped.希望有所帮助。

你可以阅读这个文档。这个概念在这里有很好的解释http://developer.android.com/training/basics/fragments/communicating.html

I'm working on a similar project and I guess my code may help in the above situation我正在做一个类似的项目,我想我的代码可能对上述情况有所帮助

Here is the overview of what i'm doing这是我正在做的事情的概述

My project Has two fragments Called " FragmentA " and "FragmentB "我的项目有两个片段叫做“ FragmentA ”和“FragmentB

- FragmentA Contains one list View,when you click an item in FragmentA It's INDEX is passed to FragmentB using Communicator interface - FragmentA包含一个列表视图,当您单击FragmentA 中的一项时,它的 INDEX 使用 Communicator 接口传递给FragmentB

  • The design pattern is totally based on the concept of java interfaces that says " interface reference variables can refer to a subclass object"设计模式完全基于java接口的概念,即“接口引用变量可以引用子类对象”
  • Let MainActivity implement the interface provided by fragmentA (otherwise we can't make interface reference variable to point to MainActivity)MainActivity实现fragmentA提供的接口(否则不能让接口引用变量指向MainActivity)
  • In the below code communicator object is made to refer to MainActivity's object by using " setCommunicator(Communicatot c) " method present in fragmentA .在下面的代码通信对象由通过使用“setCommunicator(Communicatot三)”存在于fragmentA方法来指MainActivity的对象。
  • I'm triggering respond() method of interface from FrgamentA using the MainActivity's reference.我正在使用 MainActivity 的引用从FrgamentA触发接口的respond()方法。

    Interface communcator is defined inside fragmentA, this is to provide least access previlage to communicator interface.接口通信器定义在 fragmentA 中,这是为了提供对通信器接口的最少访问权限。

below is my complete working code下面是我完整的工作代码

FragmentA.java片段A.java

public class FragmentA extends Fragment implements OnItemClickListener {

ListView list;
Communicator communicater;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragmenta, container,false);
}

public void setCommunicator(Communicator c){
    communicater=c;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    communicater=(Communicator) getActivity();
    list = (ListView) getActivity().findViewById(R.id.lvModularListView);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.items, android.R.layout.simple_list_item_1);
    list.setAdapter(adapter);
    list.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);

}

public interface Communicator{
    public void respond(int index);
}

} }

fragmentB.java片段B.java

public class FragmentA extends Fragment implements OnItemClickListener {

ListView list;
Communicator communicater;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    return inflater.inflate(R.layout.fragmenta, container,false);
}

public void setCommunicator(Communicator c){
    communicater=c;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    communicater=(Communicator) getActivity();
    list = (ListView) getActivity().findViewById(R.id.lvModularListView);
    ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.items, android.R.layout.simple_list_item_1);
    list.setAdapter(adapter);
    list.setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);

}

public interface Communicator{
    public void respond(int index);
}

}

MainActivity.java主活动.java

public class MainActivity extends Activity implements FragmentA.Communicator {
FragmentManager manager=getFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentA fragA=(FragmentA) manager.findFragmentById(R.id.fragmenta);
    fragA.setCommunicator(this);


}

@Override
public void respond(int i) {
    // TODO Auto-generated method stub

FragmentB FragB=(FragmentB) manager.findFragmentById(R.id.fragmentb);
FragB.changetext(i);
}



}

Basically Implement the interface to communicate between Activity and fragment.基本上实现了Activity和Fragment之间通信的接口。

1) Main activty 1) 主营业务

public class MainActivity extends Activity implements SendFragment.StartCommunication
{

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

@Override
public void setComm(String msg) {
// TODO Auto-generated method stub
DisplayFragment mDisplayFragment = (DisplayFragment)getFragmentManager().findFragmentById(R.id.fragment2);
if(mDisplayFragment != null && mDisplayFragment.isInLayout())
{
mDisplayFragment.setText(msg);
}
else
{
Toast.makeText(this, "Error Sending Message", Toast.LENGTH_SHORT).show();
}
}
}

2) sender fragment (fragment-to-Activity) 2)发送者片段(fragment-to-Activity)

public class SendFragment extends Fragment
{
StartCommunication mStartCommunicationListner;
String msg = "hi";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View mView = (View) inflater.inflate(R.layout.send_fragment, container);
final EditText mEditText = (EditText)mView.findViewById(R.id.editText1);
Button mButton = (Button) mView.findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
msg = mEditText.getText().toString();
sendMessage();
}
});
return mView;
}

interface StartCommunication
{
public void setComm(String msg);
}

@Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
if(activity instanceof StartCommunication)
{
mStartCommunicationListner = (StartCommunication)activity;
}
else
throw new ClassCastException();

}

public void sendMessage()
{
mStartCommunicationListner.setComm(msg);
}

}

3) receiver fragment (Activity-to-fragment) 3)接收器片段(Activity-to-Fragment)

    public class DisplayFragment extends Fragment
{
View mView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mView = (View) inflater.inflate(R.layout.display_frgmt_layout, container);
return mView;
}

void setText(String msg)
{
TextView mTextView = (TextView) mView.findViewById(R.id.textView1);
mTextView.setText(msg);
}

}

I used this link for the same solution, I hope somebody will find it usefull.我将此链接用于相同的解决方案,我希望有人会觉得它有用。 Very simple and basic example.非常简单和基本的例子。

http://infobloggall.com/2014/06/22/communication-between-activity-and-fragments/ http://infobloggal.com/2014/06/22/communication-between-activity-and-fragments/

Fragment class A片段A类

public class CountryListFragment extends ListFragment{

    /** List of countries to be displayed in the ListFragment */

    ListFragmentItemClickListener ifaceItemClickListener;   

    /** An interface for defining the callback method */
    public interface ListFragmentItemClickListener {
    /** This method will be invoked when an item in the ListFragment is clicked */
    void onListFragmentItemClick(int position);
}   

/** A callback function, executed when this fragment is attached to an activity */  
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try{
        /** This statement ensures that the hosting activity implements ListFragmentItemClickListener */
        ifaceItemClickListener = (ListFragmentItemClickListener) activity;          
    }catch(Exception e){
        Toast.makeText(activity.getBaseContext(), "Exception",Toast.LENGTH_SHORT).show();
    }
}

Fragment Class B片段 B 类

public class CountryDetailsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    /** Inflating the layout country_details_fragment_layout to the view object v */
    View v = inflater.inflate(R.layout.country_details_fragment_layout, null);

    /** Getting the textview object of the layout to set the details */ 
    TextView tv = (TextView) v.findViewById(R.id.country_details);      

    /** Getting the bundle object passed from MainActivity ( in Landscape   mode )  or from 
     *  CountryDetailsActivity ( in Portrait Mode )  
     * */
    Bundle b = getArguments();

    /** Getting the clicked item's position and setting corresponding  details in the textview of the detailed fragment */
    tv.setText("Details of " + Country.name[b.getInt("position")]);     

    return v;
    }

}

Main Activity class for passing data between fragments用于在片段之间传递数据的主要活动类

public class MainActivity extends Activity implements ListFragmentItemClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}


/** This method will be executed when the user clicks on an item in the listview */
@Override
public void onListFragmentItemClick(int position) {

    /** Getting the orientation ( Landscape or Portrait ) of the screen */
    int orientation = getResources().getConfiguration().orientation;


    /** Landscape Mode */
    if(orientation == Configuration.ORIENTATION_LANDSCAPE ){
        /** Getting the fragment manager for fragment related operations */
        FragmentManager fragmentManager = getFragmentManager();

        /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        /** Getting the existing detailed fragment object, if it already exists. 
         *  The fragment object is retrieved by its tag name  *
         */
Fragment prevFrag = fragmentManager.findFragmentByTag("in.wptrafficanalyzer.country.details");

        /** Remove the existing detailed fragment object if it exists */
        if(prevFrag!=null)
    fragmentTransaction.remove(prevFrag);           

        /** Instantiating the fragment CountryDetailsFragment */
  CountryDetailsFragment fragment = new CountryDetailsFragment();

        /** Creating a bundle object to pass the data(the clicked item's   position) from the activity to the fragment */ 
        Bundle b = new Bundle();

        /** Setting the data to the bundle object */
        b.putInt("position", position);

        /** Setting the bundle object to the fragment */
        fragment.setArguments(b);           

        /** Adding the fragment to the fragment transaction */
        fragmentTransaction.add(R.id.detail_fragment_container,   fragment,"in.wptrafficanalyzer.country.details");

        /** Adding this transaction to backstack */
        fragmentTransaction.addToBackStack(null);

        /** Making this transaction in effect */
        fragmentTransaction.commit();

    }else{          /** Portrait Mode or Square mode */
        /** Creating an intent object to start the CountryDetailsActivity */
        Intent intent = new Intent("in.wptrafficanalyzer.CountryDetailsActivity");

        /** Setting data ( the clicked item's position ) to this intent */
        intent.putExtra("position", position);

        /** Starting the activity by passing the implicit intent */
        startActivity(intent);          
      }
    }
 }

Detailde acitivity class详细活动类

public class CountryDetailsActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /** Setting the layout for this activity */
    setContentView(R.layout.country_details_activity_layout);

    /** Getting the fragment manager for fragment related operations */
    FragmentManager fragmentManager = getFragmentManager();

    /** Getting the fragmenttransaction object, which can be used to add, remove or replace a fragment */
    FragmentTransaction fragmentTransacton = fragmentManager.beginTransaction();

    /** Instantiating the fragment CountryDetailsFragment */
    CountryDetailsFragment detailsFragment = new CountryDetailsFragment();

    /** Creating a bundle object to pass the data(the clicked item's position) from the activity to the fragment */
    Bundle b = new Bundle();

    /** Setting the data to the bundle object from the Intent*/
    b.putInt("position", getIntent().getIntExtra("position", 0));

    /** Setting the bundle object to the fragment */
    detailsFragment.setArguments(b);

    /** Adding the fragment to the fragment transaction */
    fragmentTransacton.add(R.id.country_details_fragment_container, detailsFragment);       

    /** Making this transaction in effect */
    fragmentTransacton.commit();

    }
}

Array Of Contries Contries 数组

public class Country {

/** Array of countries used to display in CountryListFragment */
static String name[] = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan",
        "Bhutan"
};
}

For More Details visit this link [ http://wptrafficanalyzer.in/blog/itemclick-handler-for-listfragment-in-android/] .有关更多详细信息,请访问此链接 [ http://wptrafficanalyzer.in/blog/itemclick-handler-for-listfragment-in-android/] There are full example ..有完整的例子..

getParentFragmentManager().setFragmentResultListener is the 2020 way of doing this. getParentFragmentManager().setFragmentResultListener是 2020 年的做法。 Your only limitation is to use a bundle to pass the data.您唯一的限制是使用包来传递数据。 Check out the docs for more info and examples.查看文档以获取更多信息和示例。

Some other ways其他一些方式

  • Call to getActivity() and cast it to the shared activity between your fragments, then use it as a bridge to pass the data.调用getActivity()并将其转换为片段之间的共享活动,然后将其用作传递数据的桥梁。 This solution is highly not recommended because of the cupelling it requires between the activity and the fragments, but it used to be the popular way of doing this back in the KitKat days...强烈不建议使用此解决方案,因为它需要在活动和片段之间进行杯形处理,但在 KitKat 时代,它曾经是执行此操作的流行方式......
  • Use callbacks.使用回调。 Any events mechanism will do.任何事件机制都可以。 This would be a Java vanilla solution.这将是一个 Java vanilla 解决方案。 The benefit over FragmentManager is that it's not limited to Bundles.FragmentManager的好处在于它不仅限于 Bundle。 The downside, however, is that you may run into edge cases bugs where you mess up the activity life cycle and get exceptions like IllegalStateException when the fragment manager is in the middle of saving state or the activity were destroyed.然而,不利的一面是,您可能会遇到边缘情况错误,在这种情况下,当片段管理器处于保存状态或活动被销毁时,您会弄乱活动生命周期并获得IllegalStateException之类的异常。 Also, it does not support cross-processing communication.此外,它不支持跨处理通信。

Basically here we are dealing with communication between Fragments.基本上这里我们处理的是 Fragment 之间的通信。 Communication between fragments can never be directly possible.片段之间的通信永远不可能直接成为可能。 It involves activity under the context of which both the fragments are created.它涉及创建两个片段的上下文中的活动。

You need to create an interface in the sending fragment and implement the interface in the activity which will reprieve the message and transfer to the receiving fragment.您需要在发送片段中创建一个接口,并在活动中实现该接口,该接口将重发消息并传输到接收片段。

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

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