Java – Public methods cannot be accessed from fragment objects

Public methods cannot be accessed from fragment objects… here is a solution to the problem.

Public methods cannot be accessed from fragment objects

I use Streets Of Boston’s answer here The fragment object is saved

and take out a fragment

 Fragment fragment = myPagerAdapter.getRegisteredFragments(nowPosition);
 if (fragment == null)
 {
     return; 
 }

But I can’t access public methods from the fragment object
fragment 。

This method is in fragment

 public void dowork()
 {
     WORK!
 }

public static void dowork2()
 {
     WORK!
 }

fragment .dowork(); -> Can’t find a job
fragment .dowork2(); -> DoWork2 not found

How to access?
Thank you.

Solution

If you try to call these methods on a fragment instantiated in the sample, you need to convert the fragment to your class. So, if your fragment belongs to the MyFragment class, you need to do it

 MyFragment fragment = (MyFragment) myPagerAdapter.getRegisteredFragments(nowPosition);

You will then be able to call the methods you declared in the fragment class.

Also, static methods should be called on the class, not on the instance, so it’s right to do so

 MyFragment.dowork2();

If the method is actually static.

Related Problems and Solutions