您可以有一个接口:
public interface MyInterface {
void doSomethingWithData(Object data);
}
然后在活动类中:
public class MyActivity extends Activity implements MyInterface {
...
public void doSomethingWithData(Object data) {
// save your data in database
}
...
}
并在片段中:
public class MyFragment extends Fragment {
...
private MyInterface listener;
...
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof MyInterface) {
listener = (MyInterface) context;
}
}
@Override
public void onDetach() {
listener = null;
super.onDetach();
}
...
// Somewhere in code .. where you want to send data to the activity
listener.doSomethingWithData(data);
...
}