@Override方法不会覆盖它的超类

时间:2018-02-23 09:16:54

标签: 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.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;
        }
    }
}

我不知道为什么我会遇到这个错误。请帮忙。

2 个答案:

答案 0 :(得分:3)

OnClickListener实施添加到片段中:

public class HomeFragment extends Fragment implements View.OnClickListener {
    // Your code here
}

答案 1 :(得分:0)

您无法覆盖onClick()方法,因为onclick不是Fragment的方法。 onClick()View.OnClickListener接口的抽象方法。要覆盖onClick()方法,您必须实现接口View.OnClickListener

e.g。

public class HomeFragment extends Fragment implements View.OnClickListener {

}