Search code examples
androidandroid-studioandroid-fragmentsandroid-viewpager2

Calling mainActivity method through Fragment


I have implemented fragment in viewpager and Fragment has some buttons. Also viewpager is in activity_main layout.

I want that when button is clicked then it implement a method which is mentioned in mainActivity.java.

How can I do this?

I am a beginner.


Solution

  • You can get MainActivity method from fragment like below. Make sure your methid is public if MainActivity and ViewPager are not in same package.

    ((MainActivity) getActivity()).getMethodOfMain();