Interface communication from fragment to activity issue

前端 未结 1 837
忘了有多久
忘了有多久 2021-01-24 20:55

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

相关标签:
1条回答
  • 2021-01-24 21:21

    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);
    
    0 讨论(0)
提交回复
热议问题