Search code examples
javaandroidclassfindviewbyid

non-static method <T>findViewById(int) cannot be referenced from a static context


My first app is working fine alone but now I am trying to add tabs following a tutorial but I get stuck. I've been searching and many users had same issue, I've tried those solutions but still unable to get it working fine.

My App

package es.ea1ddo.antenacubica;

import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        frecuencia = findViewById(R.id.frecuencia);
        cal3el = (Button) findViewById(R.id.calcular3);

And now this is where I am trying to copy the previous app

package es.ea1ddo.calculadoraantenascubicas;

public class TabFragment2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View v= inflater.inflate(R.layout.tab_fragment_2, container, false);

        frecuencia = EditText.findViewById(R.id.frecuencia);
        cal3el = (Button) getView().findViewById(R.id.calcular3);

I've been searching around, trying many examples and different ways but I am stuck. You can see I added getView(). before every findViewById but I am still getting same error:

non-static method findViewById(int) cannot be referenced from a static context where T is a type-variable: T extends View declared in method findViewById(int)

Please any advice? Thanks


Solution

  • In your fragment code, you have two problems.

    The first, as others have pointed out, is that View.findViewById() is a non-static method, so you would invoke it like myView.findViewById() as opposed to EditText.findViewById().

    The second relates to how the Fragment's getView() method works. This method only works after onCreateView() has returned, because getView() returns whatever onCreateView() returned. That means that you can't call getView() from within onCreateView(); it will always return null.

    Put together, your code should look like this:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View v= inflater.inflate(R.layout.tab_fragment_2, container, false);
    
        frecuencia = (EditText) v.findViewById(R.id.frecuencia);
        cal3el = (Button) v.findViewById(R.id.calcular3);
        ...
    }