Error: Non-static method 'findViewById(int)' cannot be referenced from a static context

匿名 (未验证) 提交于 2019-12-03 01:31:01

问题:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!