Sending events back to an activity with callback interface
suggest changeIf you need to send events from a fragment to an activity, one possible solution is to define a callback interface and require that the host activity implement it.
Example
Send a callback to an activity when the fragment's button is clicked
First of all, define callback interface:
public interface SampleCallback {
void onButtonClicked();
}
Next step is to assign this callback in fragment:
public final class SampleFragment extends Fragment {
private SampleCallback callback;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof SampleCallback) {
callback = (SampleCallback) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement SampleCallback");
}
}
@Override
public void onDetach() {
super.onDetach();
callback = null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.sample, container, false);
// Add button's click listener
view.findViewById(R.id.actionButton).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callback.onButtonClicked(); // Invoke callback here
}
});
return view;
}
}
And finally, implement callback in activity:
public final class SampleActivity extends Activity implements SampleCallback {
// ... Skipped code with settings content view and presenting the fragment
@Override
public void onButtonClicked() {
// Invoked when fragment's button has been clicked
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents