반응형

출처: https://stackoverflow.com/questions/9343241/passing-data-between-a-fragment-and-its-container-activity



Try using interfaces.

Any fragment that should pass data back to its containing activity should declare an interface to handle and pass the data. Then make sure your containing activity implements those interfaces. For example:

In your fragment, declare the interface...

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

Then, connect the containing class' implementation of the interface to the fragment in the onAttach method, like so:

OnDataPass dataPasser;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    dataPasser = (OnDataPass) context;
}

Within your fragment, when you need to handle the passing of data, just call it on the dataPasser object:

public void passData(String data) {
    dataPasser.onDataPass(data);
}

Finally, in your containing activity which implements OnDataPass...

@Override
public void onDataPass(String data) {
    Log.d("LOG","hello " + data);
}


반응형

+ Recent posts