Calling a method in a fragment from a separate class

做~自己de王妃 提交于 2020-01-17 02:41:24

问题


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) ((Activity) context).getMainFragment()).Method();

This just doesn't look right....


回答1:


I think you can do something like this:

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


public class MyDialogFragment extends DialogFragment {

private OnMyDialogClickListener listener;

public static DialogFragment newInstance(OnMyDialogClickListener listener) {
    DialogFragment fragment = new MyDialogFragment(listener);
    return fragment;
}

private MyDialogFragment(OnMyDialogClickListener listener) {
    this.listener = listener;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    ....
    dialog.findViewById(R.id.button).setOnClickListener(new DialogButtonsClickListener);
    return dialog
}

private final class DialogButtonsClickListener implements View.OnClickListener {

    @Override
    public void onClick(View view) {
       listener.Method();
    }
}

public static interface OnMyDialogClickListener {

    void Method();

}

}


Implement interface in your target fragment:


public class AlbumsFragment extends BaseFragment implements OnMyDialogClickListener {

    .....

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
       //show dialog
        DialogFragment myDialogFragment = MyDialogFragment.newInstance(this);
        myDialogFragment.show(getFragmentManager(), ALBUM_ACTION_TAG);
    }

    @Override
    public void Method() {
         //some code
    }
}



回答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.




回答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();



回答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.



来源:https://stackoverflow.com/questions/22482346/calling-a-method-in-a-fragment-from-a-separate-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!