سؤال

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?

هل كانت مفيدة؟

المحلول

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);

نصائح أخرى

Change with :

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

Change:

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

to:

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

Here rootView is the parent for AutoCompleteTextView. So change it with:

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete_city);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top