I\'ve recently tried to use an interface for fragment-activity communication. The idea is that when a button is pressed in a fragment, it retrieves data from an EditText in the
getActivity() but it cannot find the associated method within the fragment
This is because getActivity()
returns an Activity
, not a MainActivity
which is your custom subclass. You can easily fix this with a cast. For example, in your fragment, you can do this:
OnDataPass main = (OnDataPass) getActivity();
main.onDataPass(message);
Since such a cast is required, the interface seems to get in the way in my opinion. You can just as easily cast directly to MainActivity
:
MainActivity main = (MainActivity) getActivity();
main.onDataPass(message);