Reference FragmentActivity to external Interface

56 views Asked by At

I want to call a function in a fragment from a class. How do i attach FragmentActivity to External Interface like i attach Activities

Currently for Activity, the class contains

public interface externalInterface {
    public void gotoNext();
}

public void setActivity(externalInterface activity) {
    parentActivity = activity;
}

and i called

parentActivity.gotoNext();

Activity has

@Override
public void gotoNext() {
    //Do something
}

Similarly i need to call gotoNext() function in a fragment from the same class.

2

There are 2 answers

0
Zain On BEST ANSWER

If the function you want to call is already in the Activity then you can do something like the code below and it will work -

The key is, in the Fragment you have a method called getActivity() which you can use to access methods in your activity.

public interface ExternalInterface {
  public void gotoNext();
}

public MyActivity implments ExternalInterface {
 public void gotoNext(){
 //Do something here
 }
}

In your Fragment, you can call

 public MyFragment extends Fragment{

@Override
public void onCreateView(....){
 ((ExternalInterface )getActivity()).gotoNext();
 }
}
0
Sush On

If i am not wrong you want to use the gotoNext() in the fragments which be will there in FragmentActivty

  1. make sure fragment activity implements interface.
  2. In fragment call getActivity() can downcast to your interface and you call the method (make sure onActivityCreated() call completed)