17

I have method in fragment class. I want to call that method from main activity but I don't want to use FragmentById (or) FragmentByTag.

My fragment method:

public void setItemFromDrawer(String sourceTag, String destTag) {
    //dosomething
}

How to call above method from main activity without using FragmentById (or) FragmentByTag?

hikoo
  • 507
  • 4
  • 10
  • 20
  • 2
    when you load fragment using fragmentTransaction save fragment object and later on you can call any public method from that object – Khizar Hayat Mar 02 '16 at 12:33
  • I didn't understand.. Can you give any example code – hikoo Mar 02 '16 at 12:38
  • possible duplicate of http://stackoverflow.com/questions/10903077/calling-a-fragment-method-from-a-parent-activity?rq=1 – Jamil Mar 02 '16 at 12:40

5 Answers5

40

First create an interface

public interface MyInterface
{
    void myAction() ;
}

Your fragment must implement this interface.

public MyFragment extends Fragment implements MyInterface

In your activity, define a field of type MyInterface :

  private MyInterface listener ;

  public void setListener(MyInterface listener)
  {
     this.listener = listener ;
  }

When creating your fragment and adding it :

setListener(myFragment);

Finally, when the condtion happens that you want to call the Fragment method, just call :

listener.myAction() ; // this will call the implementation in your MyFragment class.
Farhad Faghihi
  • 11,212
  • 5
  • 30
  • 59
9

it means your calling a fragment method

((YourFragmentClass) fragment).Yourmethod();
Prasad Khode
  • 6,303
  • 11
  • 42
  • 57
user5466222
  • 161
  • 1
  • 5
7

To better explain the answer by user5466222 :

YourFragmentClass fragment = new YourFragmentClass();
((YourFragmentClass) fragment).yourmethod();
Sif
  • 145
  • 1
  • 7
  • If it was just that easy .... but it's not. `Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference` – ekashking Dec 15 '21 at 01:03
2

In Activity use something like this where you load your fragment:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(container, fragment);

transaction.addToBackStack(null); // if you want to store transaction        
transaction.commit();
currentFragment = fragment; // currentFragment is global Fragment variable

Use following line where you want to call fragment's method

currentFragment.setItemFromDrawer("sourceTag","destTag");
Rohit5k2
  • 17,529
  • 8
  • 42
  • 56
Khizar Hayat
  • 3,049
  • 2
  • 16
  • 22
-2

((YourFragment Class) fragment).Your method();

its worked form me

user5466222
  • 161
  • 1
  • 5