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
中的代码为什么我收到错误的任何想法?
答案 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);