Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing interface to Fragment

Tags:

Let's consider a case where I have Fragment A and Fragment B.

B declares:

public interface MyInterface {     public void onTrigger(int position); } 

A implements this interface.

When pushing Fragment B into stack, how should I pass reference of Fragment A for it in Bundle so A can get the onTrigger callback when needed.

My use case scenario is that A has ListView with items and B has ViewPager with items. Both contain same items and when user goes from B -> A before popping B it should trigger the callback for A to update it's ListView position to match with B pager position.

Thanks.

like image 930
Niko Avatar asked Apr 30 '14 05:04

Niko


People also ask

Can a fragment implement an interface?

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.


2 Answers

Passing interface to Fragment 

I think you are communicating between two Fragment

In order to do so, you can have a look into Communicating with Other Fragments

public class FragmentB extends Fragment{     MyInterface mCallback;      // Container Activity must implement this interface     public interface MyInterface {         public void onTrigger();     }      @Override     public void onAttach(Activity activity) {         super.onAttach(activity);          // This makes sure that the container activity has implemented         // the callback interface. If not, it throws an exception         try {             mCallback = (MyInterface ) activity;         } catch (ClassCastException e) {             throw new ClassCastException(activity.toString()                     + " must implement MyInterface ");         }     }      ... } 
like image 150
Amit Gupta Avatar answered Oct 25 '22 12:10

Amit Gupta


For Kotlin 1.0.0-beta-3595

interface SomeCallback {}  class SomeFragment() : Fragment(){      var callback : SomeCallback? = null //some might want late init, but I think this way is safer      override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {         callback = activity as? SomeCallback //returns null if not type 'SomeCallback'          return inflater!!.inflate(R.layout.frag_some_view, container, false);     } } 
like image 32
Krtko Avatar answered Oct 25 '22 11:10

Krtko