0

Hi im making a calculator on eclipse and im following this tutorial ive done everything exactly as in the video but for some reason im getting this "Cannot make a static reference to the non-static method findViewById(int) from the type Activity" error

public PlaceholderFragment() {

    int counter;
    Button add, sub;
    TextView display;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        counter = 0;
        add = (Button) findViewById(R.id.bAdd);
        sub = (Button) findViewById(R.id.bSub);
        display = (TextView) findViewById(R.id.tvDisplay);
        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter += 1;
                display.setText("Your total is " + counter);
            }
        });
        sub.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                counter -= 1;
                display.setText("Your total is " + counter);
            }
        });

        return rootView;
    }
}
matiash
  • 54,791
  • 16
  • 125
  • 154

1 Answers1

5

The Fragment class does not have a findViewById() method; the Activity does, though. The compiler is complaining because this Fragment is a static inner class of an Activity, so it thinks you're trying to call that method.

If you are trying to get a view from the Fragment layout, then change findViewById() to rootView.findViewById().

If you're trying to get a view from the Activity layout, then change it to getActivity().findViewById().

(It depends on where the bAdd button actually is).

matiash
  • 54,791
  • 16
  • 125
  • 154