How to pass data from Fragment to Activity Using Interface
USE CASE:
We want to call onBackpressed() method in the Activity when there are no Contents in View Content API
Create an interface FragmentToActivity.java
public interface FragmentToActivity {
void communicate(String comm);
}
This the Fragment from where we want to send the data MyFavouriteFragment.java
private FragmentToActivity mCallback; //Declare the listener
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallback = (FragmentToActivity) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement FragmentToActivity");
}
}
@Override
public void onDetach() {
mCallback = null;
super.onDetach();
}
private void sendData(String comm)
{
mCallback.communicate(comm);
}
In the Activity (MyFavouriteActivity.java) implement the interface and do your action
public class MyFavouriteActivity extends FragmentActivity implements FragmentToActivity {
@Override
public void communicate(String comm) {
if(comm.equals("onBackPressed"))
onBackPressed();
}
}
Comments
Post a Comment