Skip to content Skip to sidebar Skip to footer

Calling A Method In A Fragment From A Separate Class

What's the best way to call a method inside a fragment from a different class? I passed the context via getActivity() into the class. Something along the lines of ((Fragment) ((Act

Solution 1:

I think you can do something like this:

Create interface OnMyDialogClickListener and class MyDialogFragment, which will call methods of created interface

publicclassMyDialogFragmentextendsDialogFragment {

private OnMyDialogClickListener listener;

publicstatic DialogFragment newInstance(OnMyDialogClickListener listener) {
    DialogFragmentfragment=newMyDialogFragment(listener);
    return fragment;
}

privateMyDialogFragment(OnMyDialogClickListener listener) {
    this.listener = listener;
}

@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) {
    ....
    dialog.findViewById(R.id.button).setOnClickListener(newDialogButtonsClickListener);
    return dialog
}

privatefinalclassDialogButtonsClickListenerimplementsView.OnClickListener {

    @OverridepublicvoidonClick(View view) {
       listener.Method();
    }
}

publicstaticinterfaceOnMyDialogClickListener {

    voidMethod();

}
Copy

}

Implement interface in your target fragment:

publicclassAlbumsFragmentextendsBaseFragmentimplementsOnMyDialogClickListener {

    .....

    @OverridepublicvoidonViewCreated(View view, Bundle savedInstanceState) {
       //show dialogDialogFragmentmyDialogFragment= MyDialogFragment.newInstance(this);
        myDialogFragment.show(getFragmentManager(), ALBUM_ACTION_TAG);
    }

    @OverridepublicvoidMethod() {
         //some code
    }
}

Solution 2:

It depends what are you doing.

If the operation was issued from a Fragment, you should pass a Fragment instance to a class or method that does it.

If that's an event like "user logged out" or "sdcard removed" you should send a local broadcast and register a BroadcastReceiver in the Fragment.

Solution 3:

Two methods I use frequently:

//#1 interface method in turn calls fragment;
((SomeInteraceOrSuperClass) getActivity).intefaceMethod();


//#2 hashmap = fragment directory;
TitleFrag titlefrag = (TitleFrag) getActivity().m_mapFrags.get(KEY_TITLEFRAG);
titleFrag.method();

Solution 4:

This way -> https://developer.android.com/training/basics/fragments/communicating.html (interfaces and magic)

Please, check android developers often. It contains many awnsers on good pratices.

Post a Comment for "Calling A Method In A Fragment From A Separate Class"