Search code examples
androidandroid-fragmentsandroid-pageradapter

findViewById is not defined by Fragment


AutoCompleteTextView autoCompView = 
          (AutoCompleteTextView) findViewById(R.id.autocomplete_city);

Gives me an error

The method findViewById is undefined for the type CityFragment.

with:

public class CityFragment extends Fragment {

    public CityFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.city,
                    container, false);

    AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) findViewById(R.id.autocomplete_city);

        autoCompView.setAdapter(
                       new PlacesAutoCompleteAdapter(this, R.layout.list_item)
                );

    return rootView;
    }
}

I basically just copied the code from https://developers.google.com/places/training/autocomplete-android

Any ideas why I get the error?


Solution

  • That is because indeed Fragment does not have such method findViewById(). Instead, you should use the rootView to access it.

    AutoCompleteTextView autoCompView = 
                    (AutoCompleteTextView)rootView.findViewById(R.id.autocomplete_city);