2
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

4 回答 4

4

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

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView)rootView.findViewById(R.id.autocomplete_city);
于 2013-09-27T17:13:12.510 回答
2

更改为:

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete_city);
于 2013-09-27T17:13:41.663 回答
2

改变:

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

至:

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete_city);
于 2013-09-27T17:14:43.737 回答
1

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

AutoCompleteTextView autoCompView = 
                (AutoCompleteTextView) rootView.findViewById(R.id.autocomplete_city);
于 2013-09-27T17:43:43.530 回答