Call method in main class from static fragment cla

2019-07-04 05:11发布

问题:

I have a fragment class and I want to call a method in the "main" class of my activity. The fragment class is static so that is probably whats causing the problem although I have to keep it static. I want to be able to do something like this from inside my static class: Method(); I've tried: getActivity().Method(); Although that didn't work. What should I do?

回答1:

You should be able to cast the activity returned to your specific class to access the public methods.

If your main class is called MainActivity and you have some public method Method then you could do the following from your fragment method:

((MainActivity) getActivity()).Method();

Alternatively you could use the event callback pattern described in the fragment documention.