Send data between fragments in a pagerAdapter

后端 未结 1 1302
星月不相逢
星月不相逢 2021-01-24 23:35

Hello I am trying to send data between two fragments, (armarFragment to cocinaFragment) but I dont know how do it, because both are in the same Activity (tabsActivity) which imp

相关标签:
1条回答
  • 2021-01-25 00:17

    Ok, as android guidelines says, you must create an interface in your fragment. For example:

    public class armarFragment extends Fragment implements View.OnClickListener{
        ...
        private armarFragmentListener mListener;
    
        public interface armarFragmentListener {
            void onEnviar ();
        }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (armarFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement armarFragmentListener ");
        }
    }
    
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnEnviarALaCocina:
                //Do what you want.
                mListener.onEnviar(/*Change interface to pass arguments if you want*/);
            break;
        }
    }
    

    Your activity must implements that interface and do what corresponds, for example call the methods of the fragment to get the data. When you have the data you can pass it to the new fragment as arguments or otherwise.

    When you create a blank fragment in android studio it put that structure on the class by default. Create a new blank fragment and take a look at it.

    0 讨论(0)
提交回复
热议问题