Как вызвать фрагмент из фрагмента, используя в проекте Navigation Drawer - PullRequest
1 голос
/ 26 июня 2019

У меня есть проект Navigation Drawer с несколькими фрагментами. В одном случае мне нужно вызвать фрагмент из другого фрагмента. Но я получаю ошибку ниже.

E / AndroidRuntime: FATAL EXCEPTION: main Процесс: pe.soltec.yupay17, PID: 4404 java.lang.RuntimeException: pe.soltec.yupay17.MainActivity@acf9ed30 должен реализовывать OnFragmentInteractionListener at pe.soltec.yupay17.PinkFragment.onAttach (PinkFragment.java:83) на android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1404) на android.support.v4.app.FragmentTransition.addToFirstInLastOut (FragmentTransition.java:1195) на android.support.v4.app.FragmentTransition.calculateFragments (FragmentTransition.java:1078) на android.support.v4.app.FragmentTransition.startTransitions (FragmentTransition.java:117) на android.support.v4.app.FragmentManagerImpl.executeOpsTogether (FragmentManager.java:2408) на android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute (FragmentManager.java:2366) на android.support.v4.app.FragmentManagerImpl.execPendingActions (FragmentManager.java:2273) на android.support.v4.app.FragmentManagerImpl $ 1.run (FragmentManager.java:733) на android.os.Handler.handleCallback (Handler.java:733) на android.os.Handler.dispatchMessage (Handler.java:95) на android.os.Looper.loop (Looper.java:136) на android.app.ActivityThread.main (ActivityThread.java:5017) в java.lang.reflect.Method.invokeNative (родной метод) в java.lang.reflect.Method.invoke (Method.java:515) на com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:779) на com.android.internal.os.ZygoteInit.main (ZygoteInit.java:595) at dalvik.system.NativeStart.main (собственный метод)

Я пытался назвать это так, как я называю фрагмент в основной деятельности.

getSupportFragmentManager().beginTransaction().replace(R.id.content_main,miFragment).commit();

package pe.soltec.yupay17;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class RedFragment extends Fragment
   implements PinkFragment.OnFragmentInteractionListener  {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public RedFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RedFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RedFragment newInstance(String param1, String param2) {
        RedFragment fragment = new RedFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_red, container, false);
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    public void LlamarPink(View view){
//        Toast.makeText(getActivity(), "You clicked on Item 1",
//                Toast.LENGTH_LONG).show();
        Fragment fragment2 = new PinkFragment();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container, fragment2);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
}

Я хочу показать новый фрагмент в content_main.

...