I am using Android Studio (Beta), and while using this java code in \'onCreateView()\', I get an error.
ListView listView = (ListView) findViewById(R.id.some
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.
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);
If you are using it in an static AsyncTask, or any other class, you can pass the activity as a parameter to a method or constructor, for example:
activity onCreate:
//Pass activity variable (this)
new Main2Activity.MyTask().execute(this);
class inside activity:
private static class MyTask extends AsyncTask<Object, Void, String> {
Main2Activity activity;
@Override
protected String doInBackground(Object... params) {
activity = (Main2Activity)params[0];
....
}
@Override
protected void onPostExecute(String str) {
// Use parameter activity passed to class
WebView webView = activity.findViewById(R.id.web_view);
webView.loadData(str, "text/html; charset=UTF-8", null);
}
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);
@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.