可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am using Android Studio (Beta), and while using this java code in 'onCreateView()', I get an error.
ListView listView = (ListView) findViewById(R.id.someListView);
This is the error:
Non-static method 'findViewById(int)' cannot be referenced from a static context
How do I fix this?
回答1:
Assuming you have a static fragment inner class inside an activity: you're trying to call the activity's findViewById()
which you cannot in a static inner class that doesn't hold a reference to the parent.
In onCreateView()
you need to call it on the root view you just inflated, e.g.
ListView listView = (ListView) rootView.findViewById(R.id.someListView);
回答2:
onCreateView()
shouldn't be a static method (I'm assuming you are defining it within an Activity class), so you must be doing something wrong.
回答3:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.frag_layout, container, false); ListView listView = (ListView) view.findViewById(R.id.listviewID); context = getActivity(); return view; }
You can implement this now... Use view variable to access xml ui things in oncreateView and getActivity().findViewById(...) to access other then onCreateView() Method.
回答4:
Inside Activity class
static ListView listView; listView = (ListView) this.findViewById(R.id.someListView);
OR
to create inside fragmentClass(static)
static ListView listView; listView = (ListView) getActivity().findViewById(R.id.someListView);