Java @重写方法不会从其超类重写

Java @重写方法不会从其超类重写,java,android,fragment,android-imagebutton,Java,Android,Fragment,Android Imagebutton,我刚开始为我们的论文学习java 为什么@Override方法不从它的超类重写 import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.suppo

我刚开始为我们的论文学习java

为什么@Override方法不从它的超类重写

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageButton;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment
{
    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View home = inflater.inflate(R.layout.fragment_home, container, false);

        //ImageButton
        ImageButton imageButton = (ImageButton)         
        home.findViewById(R.id.imageButton1);
        ImageButton button2 = (ImageButton)  
        home.findViewById(R.id.imageButton2);
        imageButton.setOnClickListener((View.OnClickListener) this);
        button2.setOnClickListener((View.OnClickListener) this);

        return home;
    }

   @Override
   public void onClick(View v)
   {
        int viewId = v.getId();
        switch (viewId)
        {
            //if imagebutton1 is clicked
            case R.id.imageButton1:
                Intent newActivity  = new Intent(HomeFragment.this.getActivity(), Tilapia.class);
                startActivity(newActivity);
                break;

            //button2
            case R.id.imageButton2:
                Intent newActivity2 = new Intent(HomeFragment.this.getContext(), Crab.class);
                startActivity(newActivity2);
                break;

            default:
                break;
        }
    }
}
我不知道我为什么会犯这个错误。请提供帮助。

将OnClickListener实现添加到片段中,如:

public class HomeFragment extends Fragment implements View.OnClickListener {
    // Your code here
}
您不能重写onClick方法,因为onClick不是片段的方法。 onClick是View.onClick Listener接口的抽象方法。要重写onClick方法,必须实现interface View.OnClickListener

e、 g


我猜是因为你的片段不是一个监听器?您正在通过强制转换将其传递给setOnClickListener,但是您的类定义声明它只扩展了片段,并且没有实现接口OnClickListener
public class HomeFragment extends Fragment implements View.OnClickListener {

}