Fragment没有定义findViewById

时间:2013-09-27 17:12:02

标签: android android-fragments android-pageradapter

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

给我一​​个错误

  

对于CityFragment类型,方法findViewById未定义。

使用:

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

我基本上只是复制了https://developers.google.com/places/training/autocomplete-android

中的代码

为什么我收到错误的任何想法?

4 个答案:

答案 0 :(得分:4)

这是因为确实Fragment没有这样的方法findViewById()。 相反,您应该使用rootView来访问它。

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

答案 1 :(得分:2)

更改为:

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

答案 2 :(得分:2)

变化:

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

为:

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

答案 3 :(得分:1)

这里的rootView是AutoCompleteTextView的父级。所以改为:

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