Linking multiple fragments to activity

here we go again. I am writing an application using fragments. Stefan de Bruyne suggested that this would be better than using the outdated TabHost, and he was right, thanks Stefan.

Finally, I received a message from one fragment to me. Working thanks to the help of other members (you know who you are, thanks to everyone).

Now I have what, hopefully, is the last issue. My application has a TextBox at the top, which is part of the Activity, a constant ListFragment on the left and a FrameLayout on the right so that various fragments can be displayed.

Is there a way to create a common "listener" if you like in Office, with which all different fragments can talk?

To get the data passing fragments, I used the following.

Mainactivity

import com.example.fragger.CoreFragment.OnDataPass;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;

public class MainActivity extends Activity implements OnDataPass {

and fragment code: -

package com.example.fragger;


import android.app.Activity;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.view.View.OnClickListener;


public class CoreFragment extends Fragment{

int index;
Button Button1,Button2,Button3;
String Str,data;
OnDataPass dataPasser;

@Override
public void onAttach(Activity a) {
    super.onAttach(a);
        dataPasser = (OnDataPass) a;
}


public static CoreFragment newInstance(int index) {
    CoreFragment coreFragment = new CoreFragment();
    coreFragment.index = index;
    return coreFragment;
}


public interface OnDataPass {
    public void onDataPass(String data);

}

This is good and good until I show another fragment in my frame (e.g. PlaceFragment). Since onDataPass is imported from CoreFragment and implemented, I cannot use it with anything else.

Is there any way around this?

Thanks to everyone in advance. Gary

0
source share
1 answer

For communication between fragments you can use EventBus. EventBus makes your activity and fragments loosely coupled.

The first step is to determine the type of EventType. For instance:CarSelectedEvent

When choosing a car (or some type of text in your case) CarSelectedEvent should be placed on the EventBus. Example:

eventBus.post(new CarSelectedEvent("volvo"));

All fragments or actions interested in an event must implement a method called:

onEvent(CarSelectedEvent event){
... update your view
}

, 3 , , CarSelectedEvent . (, ) . - , .

EventBus https://github.com/greenrobot/EventBus.

+1

All Articles