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

后端 未结 5 1796
天命终不由人
天命终不由人 2020-12-31 05:27

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         


        
5条回答
  •  萌比男神i
    2020-12-31 06:26

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

提交回复
热议问题