Android Studio获得"必须实现OnFragmentInteractionListener"

时间:2016-05-17 12:43:28

标签: android android-fragments

我得到了一个说#34;必须实现OnFragmentInteractionListener,我已经拥有它...

我看过这里提出的每一个问题,没有人帮助我。

有人可以帮助我吗?

ERROR:

FATAL EXCEPTION: main
     Process: com.example.android.navigationdrawer, PID: 5916
     java.lang.RuntimeException: com.example.android.navigationdrawer.MainActivity@3aefae64 must implement OnFragmentInteractionListener
         at com.example.android.navigationdrawer.FragmentCamera.onAttach(FragmentCamera.java:83)
         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1019)
         at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
         at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
         at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
         at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
         at android.os.Handler.handleCallback(Handler.java:739)
         at android.os.Handler.dispatchMessage(Handler.java:95)
         at android.os.Looper.loop(Looper.java:135)
         at android.app.ActivityThread.main(ActivityThread.java:5930)
         at java.lang.reflect.Method.invoke(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:372)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)    

MAINACTIVITY(扩展到OnFragmentInteractionListener)

package com.example.android.navigationdrawer;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, FragmentCamera.OnFragmentInteractionListener {

主要活动(FragmentCamera @Override)

@Override
public void onFragmentInteraction(Uri uri) {


}

主要活动(在职)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

主要活动(碎片交易)

    boolean FragmentTransaction = false;
            Fragment fragment = null;


            //Camera

            if (id == R.id.nav_camera) {

                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                startActivity(intent);

                ImageView mImageView = (ImageView) findViewById(R.id.Galley1);



            //Galley

            } else if (id == R.id.nav_gallery) {

                fragment = new FragmentCamera();
                FragmentTransaction = true;
}

...

        if(FragmentTransaction) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.drawer_layout, fragment)
                    .commit();

            item.setChecked(true);
            getSupportActionBar().setTitle(item.getTitle());
        }

FRAGMENTCAMERA

package com.example.android.navigationdrawer;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragmentCamera.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragmentCamera#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentCamera extends Fragment {
    // 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 FragmentCamera() {
        // 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 FragmentCamera.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentCamera newInstance(String param1, String param2) {
        FragmentCamera fragment = new FragmentCamera();
        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) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_camera, 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;
    }

    /**
     * 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);
    }
}

如果您需要更多代码,请注释,我会添加它!

3 个答案:

答案 0 :(得分:45)

从片段中移除onAttach方法,然后就可以了。

答案 1 :(得分:2)

只需删除此行:

throw RuntimeException(context.toString() + " must implement OnFragmentInteractionListener")

无需删除整个方法。

答案 2 :(得分:2)

这就是上述解决方案消除错误的原因。 FragmentCamera.java 的替代 onAttach 方法内的 if语句正在检查片段的父活动是否实现了 OnFragmentInteractionListener 接口,该接口在 FragmentCamera.java 中定义。如果父活动未实现该接口,则相应的 else语句引发错误。该接口很有用,但不是必需的。

顺便说一句, onAttach 是片段的第一个生命周期方法,并且“一旦片段与其活动相关联,就会被调用”。它不建议使用的版本是:onAttach(Activity)。 它的新版本是:onAttach(Context)。希望这对某人有帮助。